﻿Imports System.Math
Public Class _default
    Inherits System.Web.UI.Page
    Dim MySearch As String()
    Dim MyCommand As New SqlCommand
    Dim MyConnection As New SqlConnection
    Dim MyDA, MakesDA As New SqlDataAdapter
    Dim MyReader As SqlDataReader
    Dim MyDS = New DataSet
    Dim MySQL, BtnName, MyLetter, NowDateTime, UserName, StrUserID, MyLocale, NoofItems, PostBackControl As String
    Dim QuoteID, LineItem, UserID, UserCountryID, UserDepartmentID, UserAccess As Integer
    Dim TempDepartment, TempLocale, DeliveryMonth, OEMSailListID, TblOptionCount, CBCount, RowCount As Integer
    Dim NumberHours As Double
    Dim AddingBoat, AllDates As Boolean
    Dim BoatData As String()
    Dim ArrayOptionID(20) As String
    Dim LineItemCtrl As Control
    Dim sqlTran As SqlTransaction
    Dim DelDate As Date

    Dim NewTab, Display, YarnTypeChanged, IsNylon, UpdateAWS, YardPriceList, UpdateDate, CheckOptions, Reefs, RepeatCosts As Boolean
    Dim TblRow As New TableRow
    Dim TblCell As New TableCell
    Dim MyLbl As Label
    Dim MyTB As TextBox
    Dim MyCB As New CheckBox
    Dim Calculation As New dpicalculations
    'Dim sqlTran As SqlTransaction
    Dim myLB As Button


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim conn As String = System.Configuration.ConfigurationManager.AppSettings("ConnSQL")
        MyConnection = New SqlConnection(conn)
        Page.MaintainScrollPositionOnPostBack = True
        If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
        If Not Page.IsPostBack Then ' values are initialised
            If ViewState("QuoteID") = 0 Then Call WriteQuote()
            ViewState("LineItem") = 1 : ViewState("MaxLineItem") = 1 : ViewState("FilmTypeID") = 2
            LblFilm.Text = "Mylar" : ViewState("DPIID") = 0 : TblCMM.Visible = False
            ViewState("CostSailTypeID") = 26 : DDLTier.SelectedValue = 5
            ': LblDealerPriceCurrency.Visible = False
            'TabPanel1.Text = "Cruise Main PE" : 
            ViewState("IsNylon") = False : ViewState("GenSailTypeID") = 1 : ViewState("TotalOptions") = 0
            ViewState("BoatGenID") = 0 ' LblDealerPrice.Visible = False : LblDealerPriceCurrency.Visible = False
            'BtnTransfer.Visible = False
            'Call LoadUsage()
            ' Call LoadTier()
            Call LoadRaceCruise()
            Call LoadDPI()
            For i = 1 To 45
                DDLAWS.Items.Add(i)
            Next
            DDLAWS.SelectedIndex = 0
            'LblDDLCut.Visible = False : DDLCut.Visible = False
            TblCMM.Visible = False : TblWeight.Visible = False : lblNotes.Visible = False
            'If IsNumeric(QuoteID) Then ' coming from the find quote page
            '    If QuoteID > 0 Then
            '        ViewState("QuoteLineItemID") = QuoteLineItemID
            '        ViewState("LineItem") = 1
            ' Call FindAllLineItems(1)
            '        Call FindLineItemDetails()
            '        '  Exit Sub
            '        Call FillCalculations()
            '        Call FindCosts()
            '        Call FindOptions()
            '        Call LoadCut()
            '    Else
            Call LoadBoatDetails()
            Call LoadSailType()
            Call LoadConstruction()
            Call Construction_IndexChanged()
            'Call LoadYarnType()
            Call LoadSurfaces()
            'End If
            '    End If
        Else
            Try
                PostBackControl = GetPostBackControl(sender).ID
                lblmessage.Text = PostBackControl
                lblmessage.Visible = True
                If PostBackControl = "RBRaceCruise" Then
                    Call RaceCruise_IndexChanged()
                    UpdateDate = True '
                    CheckOptions = True
                ElseIf PostBackControl = "TBBoatType" Then 'CPnlSummary_ClientState
                    Call IBSearch_Click()
                    '    ViewState("QuoteLineItemID") = QuoteLineItemID
                    '    UpdateDate = True '
                    'ElseIf PostBackControl = "IBtnDelete" Then
                    '    Call DeleteLineItem()
                    '    ViewState("QuoteLineItemID") = QuoteLineItemID
                    'ElseIf PostBackControl = "DDLTier" Then
                    '    Call Tier_IndexChanged()
                    '    UpdateDate = True '
                    '    CheckOptions = True
                ElseIf PostBackControl = "DDLConstruction" Then
                    Call Construction_IndexChanged()
                    UpdateDate = True '
                    CheckOptions = True
                ElseIf PostBackControl = "DDLSailType" Then
                    Call SailType_IndexChanged()
                    UpdateDate = True '
                    CheckOptions = True
                    UpdateAWS = True
                ElseIf PostBackControl = "DDLYarnType" Then
                    YarnTypeChanged = True
                    Call YarnType_IndexChanged()
                    UpdateDate = True '
                ElseIf PostBackControl = "DDLTop" Then
                    Call FindBottom(DDLTopSurface.SelectedValue)
                    UpdateDate = True '
                ElseIf PostBackControl = "DDLBot" Then
                    UpdateDate = True '
                    'ElseIf PostBackControl = "TBLuff" Then
                    '    Call Luff_Changed()
                    '    UpdateDate = True '
                    'ElseIf PostBackControl = "TBLporFoot" Then
                    '    Call Luff_Changed()
                    '    UpdateDate = True '
                ElseIf PostBackControl = "DDLCSupplier" Then
                    Call Supplier_IndexChanged()
                    UpdateDate = True '
                    'ElseIf PostBackControl = "DDLCut" Then
                    '    LblCut.Text = DDLCut.SelectedItem.Text
                ElseIf PostBackControl = "TBBoatType" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "DDLType" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "DDLRig" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBI" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBJ" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBBoatName" Then
                    UpdateDate = True '
                ElseIf PostBackControl = "TBP" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBE" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBPy" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBEy" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBLOA" Then
                    If IsNothing(Calculation.CodeLetter) Or Calculation.CodeLetter = "M" Then
                        Calculation.Luff = TBP.Text / 1000
                        Calculation.LPorFoot = TBE.Text / 1000
                        Calculation.CodeLetter = "M"
                    Else
                        Calculation.Luff = TBJ.Text / 1000
                        Calculation.LPorFoot = TBI.Text / 1000
                    End If
                    Calculation.LoadFactorAdjuster = 1
                    Calculation.CMMperDPI = 6.7

                    'Call LoadTier()
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBISP" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBSPL" Then
                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                ElseIf PostBackControl = "TBSTL" Then

                    Call CheckBoatMeaurements()
                    Call UpdateAllLineItems(2)
                    UpdateDate = True '
                    'ElseIf PostBackControl = "Imgbtnarea" Then
                    '    Call EnableArea()
                    'ElseIf PostBackControl = "IbAWS" Then
                    '    Call EnableAWS()
                    'ElseIf PostBackControl = "TBInputArea" Then
                    '    Call NewArea()
                    '    UpdateDate = True '
                    'ElseIf PostBackControl = "DDLAWS" Then
                    '    Call NewAWS()
                    '    UpdateDate = True '
                    'ElseIf PostBackControl = "TBDiscount" Then
                    '    Call TBDiscount_TextChanged()
                    '    UpdateDate = True '
                ElseIf Left(PostBackControl, 4) = "Sail" Then
                    Call FindLineItem()
                    'ElseIf PostBackControl = "BtnAdd" Then
                    '    ViewState("GenSailTypeID") = 1
                    '    Call CreateNewLineItemDetails()
                    '    UpdateDate = True '
                Else
                End If
            Catch ex As Exception
                PostBackControl = "Option"
            End Try
            If PostBackControl <> "IBtnDelete" Then
                Call FillCalculations()
                Call FindCosts()
                Call FindOptions()
            End If
        End If
    End Sub


    Private Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        If Page.IsPostBack Then
            Call FillScreen()
            Call UpdateFile()
            If UpdateDate = True Then '
                Call UpdateQuote(TBBoatType.Text, TBLOA.Text, TBI.Text, TBJ.Text, TBP.Text, TBE.Text, TBISP.Text, TBSPL.Text, RBLBoatType.SelectedValue, ViewState("BoatGenID"), DDLRig.SelectedValue)
            End If
        End If
        If IsNumeric(ViewState("BoatGenID")) And ViewState("BoatGenID") <> 0 Then
            ImBoat.ImageUrl = "images/BoatImages/" & ViewState("BoatGenID") & ".jpg"
            ImBoat.Visible = True
        Else
            ImBoat.Visible = False
        End If
        If MyConnection.State <> ConnectionState.Closed Then MyConnection.Close()
        Call MakePicture()
        lblQuoteID.Text = ViewState("QuoteID")
        Call CreateSummary()
     End Sub

    Sub LoadBoatDetails()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Type").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select BoatTypeID, BoatType from BoatType_Tbl"
         MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "Type")
        RBLBoatType.DataSource = MyDS.Tables("Type")
        RBLBoatType.DataTextField = "BoatType"
        RBLBoatType.DataValueField = "BoatTypeID"
        RBLBoatType.DataBind()
        Try
            RBLBoatType.SelectedIndex = 0
        Catch ex As Exception
        End Try

        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Rig").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select BoatRigGrpID, BoatRigGrp from BoatRigGrp_Tbl"
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "Rig")
        DDLRig.DataSource = MyDS.Tables("Rig")
        DDLRig.DataTextField = "BoatRigGrp"
        DDLRig.DataValueField = "BoatRigGrpID"
        DDLRig.DataBind()
        Try
            DDLRig.SelectedIndex = 1
        Catch ex As Exception
        End Try

    End Sub

    Function FindPicture(ByVal BoatGenID As String) As String
        Dim PdfPath As String
        PdfPath = MapPath("images/BoatImages")
        '***

        Dim filesBriefing() As String = IO.Directory.GetFiles(PdfPath)

        '*** Briefing
        For i = 0 To filesBriefing.GetUpperBound(0)
            Dim file As New System.IO.FileInfo(filesBriefing(i))
            If BoatGenID = Left(file.Name, file.Name.Length - 4) Then
                ViewState("BoatPictureVisible") = True
                Return "images/BoatImages/" & BoatGenID & ".jpg"
                 Exit Function
            End If
        Next
         Return "images/CSFLogo.PNG"
    End Function

    Private Sub IBSearch_Click()
        PnlDGContainer.Visible = True
        Call BindDataGrid()
     End Sub

    Function FindSQL(ByVal SearchType)
        If SearchType = 3 Then

            Try
                MySearch = (Split(TBBoatType.Text, Chr(32)))
                If TBBoatType.Text = "" Then
                    NoofItems = 0
                Else
                    NoofItems = UBound(MySearch) + 1
                End If
            Catch
                NoofItems = 1
                MySearch(0) = TBBoatType.Text
            End Try
            Select Case NoofItems
                Case 1
                    MySQL = "Select * from [Boat_Tbl_View] where manufacturer like '" & Trim(MySearch(0)) & "%' or boatrange like '" & Trim(MySearch(0)) & "%' or boatmodel = '" & Trim(MySearch(0)) & "' or boattype  = '" & Trim(MySearch(0)) & "' or boatname   = '" & Trim(MySearch(0)) & "'"
                Case 2
                    MySQL = "Select * from [Boat_Tbl_View] where manufacturer like '" & Trim(MySearch(0)) & "%' or boatrange like '" & Trim(MySearch(0)) & "%' or boatmodel = '" & Trim(MySearch(0)) & "' or boattype  = '" & Trim(MySearch(0)) & "' or boatname   = '" & Trim(MySearch(0)) & "' or  manufacturer like '" & Trim(MySearch(1)) & "%' or boatrange like '" & Trim(MySearch(1)) & "%' or boatmodel = '" & Trim(MySearch(1)) & "' or boattype  = '" & Trim(MySearch(1)) & "' or boatname   = '" & Trim(MySearch(1)) & "'"
                Case 3
                    MySQL = "Select * from [Boat_Tbl_View] where manufacturer like '" & Trim(MySearch(0)) & "%' or boatrange like '" & Trim(MySearch(0)) & "%' or boatmodel = '" & Trim(MySearch(0)) & "' or boattype  = '" & Trim(MySearch(0)) & "' or boatname   = '" & Trim(MySearch(0)) & "' or  manufacturer like '" & Trim(MySearch(1)) & "%' or boatrange like '" & Trim(MySearch(1)) & "%' or boatmodel = '" & Trim(MySearch(1)) & "' or boattype  = '" & Trim(MySearch(1)) & "' or boatname   = '" & Trim(MySearch(1)) & "' or  manufacturer like '" & Trim(MySearch(2)) & "%' or boatrange like '" & Trim(MySearch(2)) & "%' or boatmodel = '" & Trim(MySearch(2)) & "' or boattype  = '" & Trim(MySearch(2)) & "' or boatname   = '" & Trim(MySearch(2)) & "'"
                Case 4
                    MySQL = "Select * from [Boat_Tbl_View] where manufacturer like '" & Trim(MySearch(0)) & "%' or boatrange like '" & Trim(MySearch(0)) & "%' or boatmodel = '" & Trim(MySearch(0)) & "' or boattype  = '" & Trim(MySearch(0)) & "' or boatname   = '" & Trim(MySearch(0)) & "' or  manufacturer like '" & Trim(MySearch(1)) & "%' or boatrange like '" & Trim(MySearch(1)) & "%' or boatmodel = '" & Trim(MySearch(1)) & "' or boattype  = '" & Trim(MySearch(1)) & "' or boatname   = '" & Trim(MySearch(1)) & "' or  manufacturer like '" & Trim(MySearch(2)) & "%' or boatrange like '" & Trim(MySearch(2)) & "%' or boatmodel = '" & Trim(MySearch(2)) & "' or boattype  = '" & Trim(MySearch(2)) & "' or boatname   = '" & Trim(MySearch(2)) & "' or  manufacturer like '" & Trim(MySearch(3)) & "%' or boatrange like '" & Trim(MySearch(3)) & "%' or boatmodel = '" & Trim(MySearch(3)) & "' or boattype  = '" & Trim(MySearch(3)) & "' or boatname   = '" & Trim(MySearch(3)) & "'"
            End Select
        ElseIf SearchType = 1 Then
            Dim Searchstring As String
            Searchstring = Replace(TBBoatType.Text, " ", "")
            MySQL = "Select * from [Boat_Tbl_View] where ConcatStringShort like '%" & Searchstring & "%'"
        Else
        End If
        MySQL = MySQL & " order by BoatRange, BoatModel, BoatType"
        Return MySQL

    End Function

    Public Shared Function GetPostBackControl(ByVal page As Page) As Control

        Dim control As Control = Nothing
        Dim ctrlname As String = page.Request.Params("__EVENTTARGET")
        If ctrlname IsNot Nothing AndAlso ctrlname <> [String].Empty Then
            control = page.FindControl(ctrlname)
        Else
            Dim ctrlStr As String = [String].Empty
            Dim c As Control = Nothing
            For Each ctl As String In page.Request.Form
                If ctl.EndsWith(".x") OrElse ctl.EndsWith(".y") Then
                    ctrlStr = ctl.Substring(0, ctl.Length - 2)
                    c = page.FindControl(ctrlStr)
                Else
                    c = page.FindControl(ctl)
                End If
                If TypeOf c Is System.Web.UI.WebControls.Button OrElse TypeOf c Is System.Web.UI.WebControls.ImageButton Then
                    control = c
                    Exit For
                End If
            Next
        End If
        Return control




    End Function

    Sub CheckBoatMeaurements()
        Dim TempBoatGenID
        If Not IsNumeric(ViewState("BoatGenID")) Then
            TempBoatGenID = 0
        Else
            TempBoatGenID = ViewState("BoatGenID")
        End If
        If IsNumeric(TBI.Text) And IsNumeric(TBJ.Text) And IsNumeric(TBLOA.Text) Then
            If TBI.Text > 0 And TBJ.Text > 0 And TBLOA.Text > 0 Then
                Call UpdateQuote(TBBoatType.Text, TBLOA.Text, TBI.Text, TBJ.Text, TBP.Text, TBE.Text, TBISP.Text, TBSPL.Text, RBLBoatType.SelectedValue, TempBoatGenID, DDLRig.SelectedValue)
            End If
        ElseIf IsNumeric(TBP.Text) And IsNumeric(TBE.Text) And IsNumeric(TBLOA.Text) Then
            If TBP.Text > 0 And TBE.Text > 0 And TBLOA.Text > 0 Then
                Call UpdateQuote(TBBoatType.Text, TBLOA.Text, TBI.Text, TBJ.Text, TBP.Text, TBE.Text, TBISP.Text, TBSPL.Text, RBLBoatType.SelectedValue, TempBoatGenID, DDLRig.SelectedValue)
            End If
        Else
            Exit Sub
        End If
    End Sub

    Sub LoadRaceCruise()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("RaceCruise").Clear()
        Catch
        End Try
         MySQL = "Select UsageTypeID, UsageType from Usage_Tbl"
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        'Try
        MyDA.Fill(MyDS, "RaceCruise")
        'Catch ex As Exception
        '    LblMessage.Text = ex.ToString & "<br>"
        '    LblMessage.Visible = True
        '    Exit Sub
        'End Try
        RBRaceCruise.DataSource = MyDS.Tables("RaceCruise")
        RBRaceCruise.DataTextField = "UsageType"
        RBRaceCruise.DataValueField = "UsageTypeID"
        RBRaceCruise.DataBind()
        RBRaceCruise.SelectedIndex = 0

    End Sub

    Sub Construction_IndexChanged()
        If DDLConstruction.SelectedValue > 1 Then
            Call LoadCloth()
            DDLSupplier.Visible = True
            DDLCloth.Visible = True
            DDLTopSurface.Visible = False
            DDLDPI.Visible = False
            DDLBotSurface.Visible = False
            ViewState("FilmTypeID") = 4
            LblFilm.Visible = False
        Else
            DDLSupplier.Visible = False
             DDLCloth.Visible = False
            DDLTopSurface.Visible = True
            DDLBotSurface.Visible = True
            LblFilm.Visible = True
            DDLDPI.Visible = True
            Call LoadYarnType()
        End If
 
    End Sub

    Sub Supplier_IndexChanged()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Cloth").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "SELECT Fabric_Tbl.PartCode, Fabric_Tbl.FabricCurrent,  Fabric_Tbl.FabricID, Fabric_Tbl.GenericYarnID, (select GenericYarn_Tbl.YarnType from GenericYarn_Tbl where GenericYarn_Tbl.GenericYarnID = Fabric_Tbl.GenericYarnID) as YarnType, Fabric_Tbl.UMLHardwareSuppliersID, (select UMLHardwareSuppliersDK_Tbl.Name from UMLHardwareSuppliersDK_Tbl where UMLHardwareSuppliersDK_Tbl.UMLHardwareSuppliersDKID = Fabric_Tbl.UMLHardwareSuppliersID) as Name, Fabric_Tbl.ConstructionID from Fabric_Tbl where  Fabric_Tbl.FabricID in (select FabricGenSailType_Tbl.FabricID from FabricGenSailType_Tbl where FabricGenSailType_Tbl.GenSailTypeID = (Select GenSailTypeID from QuoteSailType_Tbl where QuoteSailtypeID=@QuoteSailtypeID)) and Fabric_Tbl.FabricID in (select FabricTier_Tbl.FabricID from FabricTier_Tbl where FabricTier_Tbl.TierID =@TierID) AND Fabric_Tbl.ConstructionID =@ConstructionID and Fabric_Tbl.UMLHardwareSuppliersID = @UMLHardwareSuppliersID order by  Fabric_Tbl.UMLHardwareSuppliersID, Fabric_Tbl.PartCode"
        MyCommand.Parameters.AddWithValue("@QuoteSailtypeID", DDLSailType.SelectedValue)
        MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        MyCommand.Parameters.AddWithValue("@UMLHardwareSuppliersID", DDLSupplier.SelectedValue)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "Cloth")
        Dim i, j As Integer
        For i = 0 To MyDS.Tables(0).Rows.Count - 1
            If MyDS.Tables("Cloth").Rows(i).Item("FabricCurrent") = True Then
                MyDS.Tables("Cloth").Rows(i).Item("PartCode") = MyDS.Tables("Cloth").Rows(i).Item("PartCode") & "  stocked"
            End If
        Next
        DDLYarnType.Items.Clear() ' This piece of coding will now fill the yarn type dropdown list depending on the yarns available from the selected fabrics
        DDLYarnType.Items.Add(New ListItem(MyDS.Tables("Cloth").Rows(0).Item("YarnType"), MyDS.Tables("Cloth").Rows(0).Item("GenericYarnID")))
        ' Response.Write("<Br>supplier ddlyarntypecount=" & DDLYarnType.Items.Count & " genyarnid=" & MyDS.Tables("Cloth").Rows(0).Item("GenericYarnID"))
        Dim TempYarnType As Integer
        TempYarnType = DDLYarnType.SelectedValue
        For i = 0 To MyDS.Tables(0).Rows.Count - 1
            For j = 0 To DDLYarnType.Items.Count - 1
                DDLYarnType.SelectedIndex = j
                If MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID") = DDLYarnType.SelectedValue Then
                    Exit For
                Else
                    If DDLYarnType.SelectedIndex = DDLYarnType.Items.Count - 1 Then
                        DDLYarnType.Items.Add(New ListItem(MyDS.Tables("Cloth").Rows(i).Item("YarnType"), MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID")))
                        '   Response.Write("<Br>supplier yarn=" & MyDS.Tables("Cloth").Rows(i).Item("YarnType") & " genyarnid=" & MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID"))
                    End If
                End If
            Next j
        Next i
        Try
            DDLYarnType.SelectedValue = TempYarnType
        Catch ex As Exception
            DDLYarnType.SelectedIndex = 0
        End Try
        For i = 0 To MyDS.Tables("Cloth").Rows.Count - 1
            If MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID") <> DDLYarnType.SelectedValue Then
                MyDS.Tables("Cloth").Rows(i).Delete()
            End If
        Next i
        DDLCloth.DataSource = MyDS.Tables("Cloth")
        DDLCloth.DataValueField = "FabricID"
        DDLCloth.DataTextField = "PartCode"
         DDLCloth.DataBind()

    End Sub

    Sub LoadYarnType()
        Dim TempYarnType
        Try
            TempYarnType = DDLYarnType.SelectedValue
        Catch ex As Exception
        End Try
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("YarnType").Rows.Clear()
        Catch ex As Exception
        End Try
        If DDLConstruction.SelectedValue = 1 Then
            MySQL = "SELECT  PriceFactor_Tbl.GenericYarnID, GenericYarn_Tbl.YarnType FROM GenericYarn_Tbl INNER JOIN PriceFactor_Tbl ON GenericYarn_Tbl.GenericYarnID = PriceFactor_Tbl.GenericYarnID WHERE PriceFactor_Tbl.ConstructionID=@ConstructionID AND PriceFactor_Tbl.TierID=5 order by GenericYarn_Tbl.YarnType"
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
            MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        Else
            MySQL = "SELECT distinct(GenericYarn_Tbl.GenericYarnID), GenericYarn_Tbl.YarnType, Fabric_Tbl.UMLHardwareSuppliersID FROM Fabric_Tbl INNER JOIN GenericYarn_Tbl ON Fabric_Tbl.GenericYarnID = GenericYarn_Tbl.GenericYarnID where Fabric_Tbl.UMLHardwareSuppliersID = @UMLHardwareSuppliersID and Fabric_Tbl.FabricID in (select FabricGenSailType_Tbl.FabricID from FabricGenSailType_Tbl where FabricGenSailType_Tbl.GensailtypeID = @GenSailTypeID and Fabric_Tbl.FabricID in (select FabricTier_Tbl.FabricID from FabricTier_Tbl where FabricTier_Tbl.TierID =@TierID)) order by GenericYarn_Tbl.YarnType"
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
            MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
            MyCommand.Parameters.AddWithValue("@GenSailTypeID", ViewState("GenSailTypeID"))
            MyCommand.Parameters.AddWithValue("@UMLHardwareSuppliersID", DDLSupplier.SelectedValue)
        End If
        lblError.Text = lblError.Text & "<br>" & "mysql=" & MySQL & "<br>Cons=" & DDLConstruction.SelectedValue & " Tier=" & DDLTier.SelectedValue & " sail=" & ViewState("GenSailTypeID") & " suppl=" & DDLSupplier.SelectedValue
        MyCommand.CommandType = CommandType.Text
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "YarnType")
        lblError.Text = lblError.Text & "<br>" & MyDS.Tables("YarnType").rows.count
        DDLYarnType.DataSource = MyDS.Tables("YarnType")
        DDLYarnType.DataTextField = "YarnType"
        DDLYarnType.DataValueField = "GenericYarnID"
        DDLYarnType.DataBind()
        If Page.IsPostBack Then
            Try
                DDLYarnType.SelectedValue = TempYarnType
            Catch ex As Exception
                DDLYarnType.SelectedIndex = 0
            End Try
        End If
    End Sub

    Sub LoadDPI()
        Try
            If DDLConstruction.SelectedValue <> 1 Then
                LblMembraneCMM.Visible = False
                LblMembCMM.Visible = False
                DDLDPI.Visible = False
                Exit Sub
            End If
        Catch
            LblMembraneCMM.Visible = False
            DDLDPI.Visible = False
         End Try
        LblMembraneCMM.Visible = True
        LblMembCMM.Visible = True
        DDLDPI.Visible = True
         MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("DPI").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select TargetDPIID, TargetDPI from TargetDPI_Tbl where Nylon=0 order by TargetDPI"
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "DPI")
        DDLDPI.DataSource = MyDS.Tables("DPI")
        DDLDPI.DataTextField = "TargetDPI"
        DDLDPI.DataValueField = "TargetDPIID".ToString
        DDLDPI.DataBind()
         Try
            DDLDPI.SelectedValue = ViewState("DPI")
        Catch ex As Exception
            DDLDPI.SelectedIndex = 0
        End Try

    End Sub

    Sub LoadSailType()
        'the reload option is designed to allow the same sail to be selected as was there before if at all possible
        Try
            MyDS.Tables("SailType").Clear()
        Catch
        End Try
        MySQL = "SELECT distinct(QuoteSailType_Tbl.SailType) AS SailType, QuoteSailType_Tbl.QuoteSailTypeID, QuoteSailType_Tbl.GenSailTypeID FROM QuoteSailType_Tbl  WHERE QuoteSailType_Tbl.GenSailTypeID = @GenSailType ORDER BY  QuoteSailType_Tbl.SailType"
        MyCommand.Parameters.AddWithValue("@GenSailType", TBCSailType.ActiveTabIndex + 1)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "SailType")
        DDLSailType.DataSource = MyDS.Tables("Sailtype")
        DDLSailType.DataValueField = "QuoteSailTypeID".ToString
        DDLSailType.DataTextField = "SailType"
         DDLSailType.DataBind()

        If DDLSailType.SelectedIndex = 0 Then Exit Sub
        MyCommand.Parameters.Clear()
        MySQL = "Select GenSailTypeID from QuoteSailType_Tbl where QuoteSailTypeID = @QuoteSailTypeID"
        MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", DDLSailType.SelectedValue)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        Calculation.GenSailTypeID = MyCommand.ExecuteScalar

    End Sub

    Sub LoadCloth()
        MyCommand.Parameters.Clear()
        Dim TempFabricID As Integer
        Try
            TempFabricID = DDLCloth.SelectedValue
        Catch ex As Exception
            TempFabricID = 176
        End Try
        Try
            MyDS.Tables("Cloth").Rows.Clear()
        Catch ex As Exception
        End Try
        If Page.IsPostBack Then
            MySQL = "SELECT Fabric_Tbl.PartCode, Fabric_Tbl.FabricCurrent, Fabric_Tbl.FabricArchived,  Fabric_Tbl.FabricID, Fabric_Tbl.GenericYarnID, (select GenericYarn_Tbl.YarnType from GenericYarn_Tbl where GenericYarn_Tbl.GenericYarnID = Fabric_Tbl.GenericYarnID) as YarnType, Fabric_Tbl.UMLHardwareSuppliersID, (select UMLHardwareSuppliersDK_Tbl.Name from UMLHardwareSuppliersDK_Tbl where UMLHardwareSuppliersDK_Tbl.UMLHardwareSuppliersDKID = Fabric_Tbl.UMLHardwareSuppliersID) as Name, Fabric_Tbl.ConstructionID from Fabric_Tbl where  Fabric_Tbl.FabricID in (select FabricGenSailType_Tbl.FabricID from FabricGenSailType_Tbl where FabricGenSailType_Tbl.GenSailTypeID = (Select GenSailTypeID from QuoteSailType_Tbl where QuoteSailtypeID=@QuoteSailtypeID)) and Fabric_Tbl.FabricID in (select FabricTier_Tbl.FabricID from FabricTier_Tbl where FabricTier_Tbl.TierID =@TierID) AND Fabric_Tbl.ConstructionID =@ConstructionID  and  Fabric_Tbl.FabricArchived <> 1  order by  Fabric_Tbl.UMLHardwareSuppliersID, Fabric_Tbl.FabricCurrent desc, Fabric_Tbl.FabricStyleID, Fabric_Tbl.PartCode"
        Else
            MySQL = "SELECT Fabric_Tbl.PartCode, Fabric_Tbl.FabricCurrent, Fabric_Tbl.FabricArchived,  Fabric_Tbl.FabricID, Fabric_Tbl.GenericYarnID, (select GenericYarn_Tbl.YarnType from GenericYarn_Tbl where GenericYarn_Tbl.GenericYarnID = Fabric_Tbl.GenericYarnID) as YarnType, Fabric_Tbl.UMLHardwareSuppliersID, (select UMLHardwareSuppliersDK_Tbl.Name from UMLHardwareSuppliersDK_Tbl where UMLHardwareSuppliersDK_Tbl.UMLHardwareSuppliersDKID = Fabric_Tbl.UMLHardwareSuppliersID) as Name, Fabric_Tbl.ConstructionID from Fabric_Tbl where  Fabric_Tbl.FabricID in (select FabricGenSailType_Tbl.FabricID from FabricGenSailType_Tbl where FabricGenSailType_Tbl.GenSailTypeID = (Select GenSailTypeID from QuoteSailType_Tbl where QuoteSailtypeID=@QuoteSailtypeID)) and Fabric_Tbl.FabricID in (select FabricTier_Tbl.FabricID from FabricTier_Tbl where FabricTier_Tbl.TierID =@TierID) AND Fabric_Tbl.ConstructionID =@ConstructionID  and  Fabric_Tbl.FabricArchived <> 1 and Fabric_Tbl.GenericYarnID=@GenericYarnID order by  Fabric_Tbl.UMLHardwareSuppliersID, Fabric_Tbl.FabricCurrent desc, Fabric_Tbl.FabricStyleID, Fabric_Tbl.PartCode"
        End If
        MyCommand.Parameters.AddWithValue("@QuoteSailtypeID", DDLSailType.SelectedValue)
        MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        If Not Page.IsPostBack Then
            MyCommand.Parameters.AddWithValue("@GenericYarnID", 4)
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        ElseIf Display <> True Then
            MyCommand.Parameters.AddWithValue("@GenericYarnID", DDLYarnType.SelectedValue)
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        ElseIf PostBackControl = "RBNylon" Then
            MyCommand.Parameters.AddWithValue("@GenericYarnID", 12)
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        ElseIf IsNylon Then
            MyCommand.Parameters.AddWithValue("@GenericYarnID", 12)
            MyCommand.Parameters.AddWithValue("@ConstructionID", 5)
        Else
            ' I have changed this back to the dropdownlist because on change of construction, there is no MyDS.Tables("LineItem") yet, but I can't remember why I had changed it to that in the first place!
            ' MyCommand.Parameters.AddWithValue("@GenericYarnID", MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID"))
            MyCommand.Parameters.AddWithValue("@GenericYarnID", DDLYarnType.SelectedValue)
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        End If
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        '  Response.Write(MySQL & " - " & DDLSailType.SelectedValue & " - " & DDLTier.SelectedValue & " - " & DDLConstruction.SelectedValue & " - " & DDLYarnType.SelectedValue) 'MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID"))
        MyDA.Fill(MyDS, "Cloth")
        Dim i, j As Integer
        For i = 0 To MyDS.Tables("Cloth").Rows.Count - 1
            If MyDS.Tables("Cloth").Rows(i).Item("FabricCurrent") = True Then
                MyDS.Tables("Cloth").Rows(i).Item("PartCode") = MyDS.Tables("Cloth").Rows(i).Item("PartCode") & "  stocked"
            End If
        Next
        Dim TempYarnType As Integer
        If Page.IsPostBack Then TempYarnType = DDLYarnType.SelectedValue
        If ViewState("IsNylon") Then YarnTypeChanged = False
        If YarnTypeChanged <> True Then
            DDLYarnType.Items.Clear() ' This piece of coding will now fill the yarn type dropdown list depending on the yarns available from the selected fabrics
            DDLYarnType.Items.Add(New ListItem(MyDS.Tables("Cloth").Rows(0).Item("YarnType"), MyDS.Tables("Cloth").Rows(0).Item("GenericYarnID")))
            '      Response.Write("<Br> ddlyarntypecount=" & DDLYarnType.Items.Count & " genyarnid=" & MyDS.Tables("Cloth").Rows(0).Item("GenericYarnID"))
            For i = 0 To MyDS.Tables("Cloth").Rows.Count - 1
                For j = 0 To DDLYarnType.Items.Count - 1
                    DDLYarnType.SelectedIndex = j
                    If MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID") = DDLYarnType.SelectedValue Then
                        '               Response.Write("<Br> ddlyarnvalue=" & DDLYarnType.SelectedValue & " genyarnid=" & MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID"))
                        Exit For
                    Else
                        If DDLYarnType.SelectedIndex = DDLYarnType.Items.Count - 1 Then
                            DDLYarnType.Items.Add(New ListItem(MyDS.Tables("Cloth").Rows(i).Item("YarnType"), MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID")))
                            '   Response.Write("<Br> yarntype=" & MyDS.Tables("Cloth").Rows(i).Item("YarnType") & " genyarnid=" & MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID"))
                        End If
                    End If
                Next j
            Next i
        End If
        If Page.IsPostBack Then
            Try
                DDLYarnType.SelectedValue = TempYarnType
            Catch
                DDLYarnType.SelectedIndex = 0
            End Try
        Else
            Try
                DDLYarnType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID")
            Catch
                DDLYarnType.SelectedIndex = 0
            End Try
        End If

        DDLSupplier.Items.Clear() ' This piece of coding will now fill the cloth supplier dropdown list depending on the suppliers available from the selected fabrics
        DDLSupplier.Items.Add(New ListItem(MyDS.Tables("Cloth").Rows(0).Item("Name"), MyDS.Tables("Cloth").Rows(0).Item("UMLHardwareSuppliersID")))
        For i = 0 To MyDS.Tables("Cloth").Rows.Count - 1
            For j = 0 To DDLSupplier.Items.Count - 1
                DDLSupplier.SelectedIndex = j
                If MyDS.Tables("Cloth").Rows(i).Item("UMLHardwareSuppliersID") = DDLSupplier.SelectedValue Then
                    Exit For
                Else
                    If DDLSupplier.SelectedIndex = DDLSupplier.Items.Count - 1 Then
                        DDLSupplier.Items.Add(New ListItem(MyDS.Tables("Cloth").Rows(i).Item("Name"), MyDS.Tables("Cloth").Rows(i).Item("UMLHardwareSuppliersID")))
                    End If
                End If
            Next j
        Next i
        DDLSupplier.SelectedIndex = 0
        ' now the cloth types that do not match the selected yarn or the selected supplier are removed from the list
        For i = 0 To MyDS.Tables("Cloth").Rows.Count - 1
            If MyDS.Tables("Cloth").Rows(i).Item("GenericYarnID") <> DDLYarnType.SelectedValue Then
                MyDS.Tables("Cloth").Rows(i).Delete()
            ElseIf MyDS.Tables("Cloth").Rows(i).Item("UMLHardwareSuppliersID") <> DDLSupplier.SelectedValue Then
                MyDS.Tables("Cloth").Rows(i).Delete()
            End If
        Next i
        DDLCloth.DataSource = MyDS.Tables("Cloth")
        DDLCloth.DataValueField = "FabricID"
        DDLCloth.DataTextField = "PartCode"
        DDLCloth.DataBind()
        Try
            DDLCloth.SelectedValue = TempFabricID
        Catch ex As Exception
            DDLCloth.SelectedIndex = 0
        End Try
    End Sub

    Sub LoadConstruction()

        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Construction").Rows.Clear()
        Catch ex As Exception
        End Try
        Dim TempConstructionID As Integer
        Try
            TempConstructionID = DDLConstruction.SelectedValue
        Catch
            TempConstructionID = 1
        End Try

         If ViewState("IsNylon") Then
            MySQL = "Select ConstructionID, Construction from ConstructionAndrew_Tbl where ConstructionID = 5 order by Construction"
         Else
            MySQL = "Select ConstructionID, Construction from ConstructionAndrew_Tbl  order by ConstructionType"
        End If
        MyCommand.CommandType = CommandType.Text
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "Construction")
        DDLConstruction.DataSource = MyDS.Tables("Construction")
        DDLConstruction.DataTextField = "Construction"
        DDLConstruction.DataValueField = "ConstructionID"
        DDLConstruction.DataBind()
        Try
            DDLConstruction.SelectedValue = TempConstructionID
        Catch ex As Exception
            DDLConstruction.SelectedIndex = 0
        End Try
        Call LoadTier()
    End Sub

    Sub LoadTier()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Tier").Rows.Clear()
        Catch ex As Exception
        End Try
        If IsNumeric(TBLOA.Text) Then
            MySQL = "Select * from Tier_Tbl where UsageTypeID = @UsageTypeID  and MaxLength > @MaxLength order by Tier"
        Else
            MySQL = "Select * from Tier_Tbl where UsageTypeID = @UsageTypeID order by Tier"
        End If
        MyCommand.Parameters.AddWithValue("@UsageTypeID", RBRaceCruise.SelectedValue)
        MyCommand.Parameters.AddWithValue("@MaxLength", TBLOA.Text)
        MyCommand.CommandType = CommandType.Text
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "Tier")
        'HQ only to see OEM tier
        If ViewState("DealerMarket") <> 22 Then
            For i = 0 To MyDS.Tables("Tier").Rows.Count - 1
                If MyDS.Tables("Tier").Rows(i).Item("TierID") = 17 Then
                    MyDS.Tables("Tier").Rows(i).Delete()
                    Exit For
                End If
            Next
        End If
        DDLTier.DataSource = MyDS.Tables("Tier")
        DDLTier.DataTextField = "Tier"
        DDLTier.DataValueField = "TierID"
         DDLTier.DataBind()

    End Sub


    Sub LoadSurfaces()
        Dim TempTop, TempBot As Integer
        Try
            TempTop = DDLTopSurface.SelectedValue
            TempBot = DDLBotSurface.SelectedValue
        Catch ex As Exception
        End Try
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("EpexTop").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select SurfaceComponent_Tbl.SurfaceComponentID, SurfaceComponent_Tbl.SurfaceComponent" & _
        " from SurfaceComponent_Tbl " & _
        " where TopSurface = 1 " & _
        " and SurfaceComponentID in (Select SurfaceCombination_Tbl.SurfaceComponent1ID " & _
        " from CombinationTier_Tbl inner join SurfaceCombination_Tbl on " & _
        " CombinationTier_Tbl.SurfaceCombinationID = SurfaceCombination_Tbl.SurfaceCombinationID" & _
        " where CombinationTier_Tbl.TierID=@TierID) "
        MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        MyCommand.CommandType = CommandType.Text
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "EpexTop")
         DDLTopSurface.DataSource = MyDS.Tables("EpexTop")
        DDLTopSurface.DataTextField = "SurfaceComponent"
        DDLTopSurface.DataValueField = "SurfaceComponentID"
        DDLTopSurface.DataBind()
         Try
            Try
                DDLTopSurface.SelectedValue = TempTop
            Catch ex As Exception
                DDLTopSurface.SelectedIndex = 0
            End Try
            Call FindBottom(DDLTopSurface.SelectedValue)
        Catch
            DDLBotSurface.Items.Clear()
            DDLBotSurface.DataSource = MyDS.Tables("EpexTop")
            DDLBotSurface.DataTextField = "SurfaceComponent"
            DDLBotSurface.DataValueField = "SurfaceComponentID"
            DDLBotSurface.DataBind()
        End Try
        Try
            DDLBotSurface.SelectedValue = TempBot
        Catch ex As Exception
            DDLBotSurface.SelectedIndex = 0
        End Try
    End Sub

    Sub FindBottom(ByVal TopID)
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("EpexBot").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "SELECT SurfaceCombination_Tbl.SurfaceComponent1ID, " & _
        " SurfaceCombination_Tbl.SurfaceComponent2ID, " & _
" (Select  SurfaceComponent_Tbl.SurfaceComponent from SurfaceComponent_Tbl " & _
" where SurfaceComponent_Tbl.SurfaceComponentID = SurfaceCombination_Tbl.SurfaceComponent2ID) " & _
" AS SurfaceComponent FROM SurfaceCombination_Tbl " & _
" WHERE SurfaceCombination_Tbl.SurfaceComponent1ID=" & TopID & " and " & _
" SurfaceCombination_Tbl.SurfaceCombinationID in (select CombinationTier_Tbl.SurfaceCombinationID from " & _
" CombinationTier_Tbl where  CombinationTier_Tbl.TierID=@TierID) "
        MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        MyCommand.CommandType = CommandType.Text
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        DDLBotSurface.Items.Clear()
        MyDA.Fill(MyDS, "EpexBot")

        DDLBotSurface.DataSource = MyDS.Tables("EpexBot")
        DDLBotSurface.DataValueField = "SurfaceComponent2ID"
        DDLBotSurface.DataTextField = "SurfaceComponent"
        DDLBotSurface.DataBind()
    End Sub

    Sub RaceCruise_IndexChanged()
        Dim TempSailTypeID As Integer
        TempSailTypeID = DDLSailType.SelectedValue
        Call LoadSailType()
        Try
            DDLSailType.SelectedValue = TempSailTypeID
        Catch
            DDLSailType.SelectedIndex = 0
        End Try
        If DDLConstruction.SelectedValue > 1 Then ' if it is not EMT
            Call LoadCloth()
        Else
            Call LoadSurfaces()
            Call LoadYarnType()
        End If

        If DDLSailType.SelectedIndex <> 0 And DDLConstruction.SelectedIndex <> 0 Then
            Call LoadYarnType()
            Call LoadDPI()
            Call FillCalculations()
         End If
        DDLAWS.SelectedIndex = DDLAWS.Items.IndexOf(DDLAWS.Items.FindByText(Round(Calculation.MaxAWS, 0)))
    End Sub

    Sub SailType_IndexChanged()
        Dim GenSailTypeID As Integer
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("NewSailType").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "SELECT QuoteSailType_Tbl.GenSailTypeID, QuoteSailType_Tbl.Furling,  CostSailType_Tbl.MaxAWSFactor, CostSailType_Tbl.MinAWSFactor, CostSailType_Tbl.MinTWS, CostSailType_Tbl.MaxTWS, CostSailType_Tbl.CodeLetter, CostSailType_Tbl.JLPMultiplier, CostSailType_Tbl.ILuffMultiplier, CostSailType_Tbl.PLuffMultiplier, CostSailType_Tbl.EFootMultiplier from QuoteSailType_Tbl inner join CostSailType_Tbl on QuoteSailType_Tbl.CostSailtypeID = CostSailType_Tbl.CostSailtypeID where QuoteSailTypeID = @QuoteSailTypeID"
        MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", DDLSailType.SelectedValue)
        MyCommand.CommandType = CommandType.Text
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "NewSailType")
        '    Response.Write("<br>" & MyDS.Tables("NewSailType").Rows(0).Item("JLPMultiplier") & "<br>")
        GenSailTypeID = MyDS.Tables("NewSailType").Rows(0).Item("GenSailTypeID")
        Calculation.GenSailTypeID = GenSailTypeID
        If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("CodeLetter")) Then
            If (MyDS.Tables("NewSailType").Rows(0).Item("CodeLetter") = "S" Or MyDS.Tables("NewSailType").Rows(0).Item("CodeLetter") = "A") And DDLTier.SelectedValue <> 23 And DDLTier.SelectedValue <> 24 Then
                ViewState("IsNylon") = True
                Calculation.Nylon = True
                ' Call LoadCut()
            Else
                ViewState("IsNylon") = False
                Calculation.Nylon = False
            End If
        End If
        If ViewState("GenSailTypeID") <> GenSailTypeID Then
            Calculation.GenSailTypeID = GenSailTypeID
            ViewState("GenSailTypeID") = GenSailTypeID
            If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("MinTWS")) Then Calculation.MinTWS = MyDS.Tables("NewSailType").Rows(0).Item("MinTWS")
            If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("MaxTWS")) Then Calculation.MaxTWS = MyDS.Tables("NewSailType").Rows(0).Item("MaxTWS")
            If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("GenSailTypeID")) Then Calculation.GenSailTypeID = MyDS.Tables("NewSailType").Rows(0).Item("GenSailTypeID")
            If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("MaxAWSFactor")) Then Calculation.MaxAWSFactor = MyDS.Tables("NewSailType").Rows(0).Item("MaxAWSFactor")
            If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("MinAWSFactor")) Then Calculation.MinAWSFactor = MyDS.Tables("NewSailType").Rows(0).Item("MinAWSFactor")
            DDLAWS.SelectedIndex = DDLAWS.Items.IndexOf(DDLAWS.Items.FindByText(Round(Calculation.MaxAWS(), 0)))
            If DDLConstruction.SelectedValue = 1 Then
                Call LoadYarnType()
            Else
                Call LoadCloth()
            End If
        End If
        If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("JLPMultiplier")) Then Calculation.FindLP = MyDS.Tables("NewSailType").Rows(0).Item("JLPMultiplier")
        If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("ILuffMultiplier")) Then Calculation.FindLuff = MyDS.Tables("NewSailType").Rows(0).Item("ILuffMultiplier")
        If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("PLuffMultiplier")) Then Calculation.FindPLuff = MyDS.Tables("NewSailType").Rows(0).Item("PLuffMultiplier")
        If Not IsDBNull(MyDS.Tables("NewSailType").Rows(0).Item("EFootMultiplier")) Then Calculation.FindEFoot = MyDS.Tables("NewSailType").Rows(0).Item("EFootMultiplier")

         BtnName = "Sail" & ViewState("LineItem")
        Dim myControl1 As Button = Page.FindControl(BtnName)
        If (Not myControl1 Is Nothing) Then
            myControl1.Text = DDLSailType.SelectedItem.Text
        End If
    End Sub

    Sub YarnType_IndexChanged()
        If DDLConstruction.SelectedValue > 1 Then ' if it is not EMT
            Call LoadCloth()
        Else
            Call LoadSurfaces()
        End If
    End Sub

    Sub UpdateAllLineItems(ByVal UpdateType)
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("LIU").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select QuoteLineItem_Tbl.*, (Select case when (Select BoatStyleID from Quote_Tbl where Quote_Tbl.QuoteID = QuoteLineItem_Tbl.QuoteID and QuoteLineItem_Tbl.LineItem=1) = 1 then (select Monomultiplier from Usage_Tbl where Usage_Tbl.UsageTypeID=QuoteLineItem_Tbl.UsageID) else (select Multimultiplier from Usage_Tbl where Usage_Tbl.UsageTypeID=QuoteLineItem_Tbl.UsageID)end) as BoatTypeMultiplier, case when QuoteLineItem_Tbl.BRP is null  then 0 else QuoteLineItem_Tbl.BRP end as BRP, (Select Currency_Tbl.ExRate from currency_Tbl  where Currency_Tbl.CurrencyID = (Select CurrencyID from Quote_Tbl  where Quote_Tbl.QuoteID =  QuoteLineItem_Tbl.QuoteID and QuoteLineItem_Tbl.LineItem=1)) as ExRate, case when QuoteLineItem_Tbl.OriginatingOEMSailListID > 0 then (select ListRetailPrice from oemsaillist_Tbl where oemsaillist_Tbl.OEMSailListID= QuoteLineItem_Tbl.OriginatingOEMSailListID) else 0 end as Listretailprice, (Select Currency_Tbl.ExRate from currency_Tbl where Currency_Tbl.axSymbol = QuoteLineItem_Tbl.BillingCurrency ) as DealerExRate,  case when   QuoteLineItem_Tbl.OptionTotal is null  then 0 else QuoteLineItem_Tbl.OptionTotal end as OptionTotal, (Select Max(Market_Tbl.CostFactor) from Market_Tbl where  MarketID=(Select Quote_Tbl.MarketID from Quote_Tbl   where Quote_Tbl.QuoteID=QuoteLineItem_Tbl.QuoteID)) as MarketCostFactor, (Select SeasonalPrice_Tbl.PriceFactor   from SeasonalPrice_Tbl where SeasonalPrice_Tbl.Weekno = @Weekno) as SeasonalPriceFactor, (select DeliveryDate from Quote_Tbl where Quote_Tbl.QuoteID=QuoteLineItem_Tbl.QuoteID) as QuoteDeliveryDate, CostSailType_Tbl.MaxTWS, CostSailType_Tbl.CostSailTypeID as CostSailTypeID, CostSailType_Tbl.SailTypeAddFactor, CostSailType_Tbl.Main, CostSailType_Tbl.CodeLetter, CostSailType_Tbl.Code2, CostSailType_Tbl.MaxAWSFactor, CostSailType_Tbl.MinAWSFactor, CostSailType_Tbl.mintws, CostSailType_Tbl.Areafactor, CostSailType_Tbl.BoatSpeedAdjuster, CostSailType_Tbl.LoadFactorAdjuster, CostSailType_Tbl.ILuffMultiplier, CostSailType_Tbl.JLPMultiplier, CostSailType_Tbl.PLuffMultiplier, CostSailType_Tbl.EFootMultiplier,  QuoteSailType_Tbl.GenSailTypeID, GenericYarn_Tbl.YarnType, QuoteSailType_Tbl.SailType, (Select Max(Headyarns_Tbl.CMMperDPI) from Headyarns_Tbl where Headyarns_Tbl.YarnTYpe=GenericYarn_Tbl.Yarntype) as CMMperDPI, (Select Construction from ConstructionAndrew_Tbl where QuoteLineItem_Tbl.ConstructionID=ConstructionAndrew_Tbl.ConstructionID) as Construction,  (Select PartCode from Fabric_Tbl where QuoteLineItem_Tbl.FabricID=Fabric_Tbl.FabricID) as Fabric from QuoteLineItem_Tbl left outer join Quotesailtype_tbl on QuoteLineItem_tbl.QuoteSailTypeID=QuoteSailType_tbl.QuoteSailTypeID left outer join CostSailType_tbl on CostSailType_Tbl.CostSailTypeID=QuoteSailType_tbl.CostSailTypeID left outer join GenericYarn_Tbl on GenericYarn_Tbl.GenericYarnID = QuoteLineItem_Tbl.GenericYarnID where QuoteLineItem_Tbl.QuoteID = @QuoteID"
        MyCommand.Parameters.AddWithValue("@QuoteID", QuoteID)
        MyCommand.Parameters.AddWithValue("@Weekno", DatePart(DateInterval.WeekOfYear, DelDate, , FirstWeekOfYear.FirstFourDays))
        MyCommand.Connection = MyConnection
        MyCommand.CommandText = MySQL
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "LIU")
        If MyDS.Tables("LIU").Rows.Count = 0 Then Exit Sub
        For i = 0 To MyDS.Tables("LIU").Rows.Count - 1

            Call NewPrice(i, UpdateType)
        Next i

    End Sub

    Sub NewPrice(ByVal Lineitem, ByVal UpdateType) ' recalculates all LineItems
        Dim TempBoatSpeed, TempArea As Double
        Dim TempDate As DateTime
        Dim TempLuff, TempLporFoot, TempAWS, TempDPIID As Integer

        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("QuoteDeliveryDate")) Then
            TempDate = MyDS.Tables("LIU").Rows(Lineitem).Item("QuoteDeliveryDate")
        Else
            TempDate = DateAdd(DateInterval.WeekOfYear, 6, DatePart(DateInterval.WeekOfYear, Now(), , FirstWeekOfYear.FirstFourDays))
        End If
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("AWS")) Then
            TempAWS = MyDS.Tables("LIU").Rows(Lineitem).Item("AWS")
        Else
            TempAWS = 0
        End If
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("Boatspeed")) Then
            TempBoatSpeed = MyDS.Tables("LIU").Rows(Lineitem).Item("Boatspeed")
        Else
            TempBoatSpeed = 0
        End If
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("DPIID")) Then
            TempDPIID = MyDS.Tables("LIU").Rows(Lineitem).Item("DPIID")
        Else
            TempDPIID = 0
        End If
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("BoatSpeed")) Then
            Calculation.MaxUpwBoatSpeed = MyDS.Tables("LIU").Rows(Lineitem).Item("BoatSpeed")
        Else
            Calculation.MaxUpwBoatSpeed = 0
        End If
        Calculation.LOA = MyDS.Tables("LIU").Rows(Lineitem).Item("LOA")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("BoatTypeMultiplier")) Then
            Calculation.BoatTypeFactor = MyDS.Tables("LIU").Rows(0).Item("BoatTypeMultiplier")
        Else
            Calculation.BoatTypeFactor = 0
        End If
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("CMMperDPI")) Then
            Calculation.CMMperDPI = MyDS.Tables("LIU").Rows(Lineitem).Item("CMMperDPI")
        Else
            Calculation.CMMperDPI = 0
        End If


        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("MinTWS")) Then Calculation.MinTWS = MyDS.Tables("LIU").Rows(Lineitem).Item("MinTWS")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("MaxTWS")) Then Calculation.MaxTWS = MyDS.Tables("LIU").Rows(Lineitem).Item("MaxTWS")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("GenSailTypeID")) Then Calculation.GenSailTypeID = MyDS.Tables("LIU").Rows(Lineitem).Item("GenSailTypeID")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("MaxAWSFactor")) Then Calculation.MaxAWSFactor = MyDS.Tables("LIU").Rows(Lineitem).Item("MaxAWSFactor")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("MinAWSFactor")) Then Calculation.MinAWSFactor = MyDS.Tables("LIU").Rows(Lineitem).Item("MinAWSFactor")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("Main")) Then Calculation.Main = MyDS.Tables("LIU").Rows(Lineitem).Item("Main")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("AreaFactor")) Then Calculation.AreaFactor = MyDS.Tables("LIU").Rows(Lineitem).Item("AreaFactor")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("BoatSpeedAdjuster")) Then Calculation.BoatSpeedAdjuster = MyDS.Tables("LIU").Rows(Lineitem).Item("BoatSpeedAdjuster")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("LoadFactorAdjuster")) Then Calculation.LoadFactorAdjuster = MyDS.Tables("LIU").Rows(Lineitem).Item("LoadFactorAdjuster")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("ILuffMultiplier")) Then Calculation.FindLuff = MyDS.Tables("LIU").Rows(Lineitem).Item("ILuffMultiplier")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("EFootMultiplier")) Then Calculation.FindEFoot = MyDS.Tables("LIU").Rows(Lineitem).Item("EFootMultiplier")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("PLuffMultiplier")) Then Calculation.FindPLuff = MyDS.Tables("LIU").Rows(Lineitem).Item("PLuffMultiplier")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("JLPMultiplier")) Then Calculation.FindLP = MyDS.Tables("LIU").Rows(Lineitem).Item("JLPMultiplier")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("CodeLetter")) Then Calculation.CodeLetter = MyDS.Tables("LIU").Rows(Lineitem).Item("CodeLetter")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("Code2")) Then Calculation.Code2 = MyDS.Tables("LIU").Rows(Lineitem).Item("Code2")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("SailTypeAddFactor")) Then Calculation.SmallSailAdjuster = MyDS.Tables("LIU").Rows(Lineitem).Item("SailTypeAddFactor")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("Luff")) Then Calculation.Luff = MyDS.Tables("LIU").Rows(Lineitem).Item("Luff") / 1000
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("LporFoot")) Then Calculation.LPorFoot = MyDS.Tables("LIU").Rows(Lineitem).Item("LporFoot") / 1000
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("Luff")) Then TempLuff = MyDS.Tables("LIU").Rows(Lineitem).Item("Luff")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("LporFoot")) Then TempLporFoot = MyDS.Tables("LIU").Rows(Lineitem).Item("LporFoot")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("InputArea")) Then TempArea = MyDS.Tables("LIU").Rows(Lineitem).Item("InputArea")


        If UpdateType = 1 Then
            TempBoatSpeed = Round(Calculation.CalcBoatSpeed, 2)
            TempAWS = Round(Calculation.MaxAWS(), 0)
            Calculation.InputAWS = TempAWS
            Call UpdateDPIDecision(Lineitem)
        ElseIf UpdateType = 2 Then
            Calculation.I = MyDS.Tables("LIU").Rows(Lineitem).Item("I") / 1000
            Calculation.J = MyDS.Tables("LIU").Rows(Lineitem).Item("J") / 1000
            Calculation.ValE = MyDS.Tables("LIU").Rows(Lineitem).Item("E") / 1000
            Calculation.P = MyDS.Tables("LIU").Rows(Lineitem).Item("P") / 1000
            Calculation.ISP = MyDS.Tables("LIU").Rows(Lineitem).Item("ISP") / 1000
            Calculation.SPL = MyDS.Tables("LIU").Rows(Lineitem).Item("Spl") / 1000
            Calculation.STL = MyDS.Tables("LIU").Rows(Lineitem).Item("Stl") / 1000
            If Calculation.Main = True Then
                TempLuff = Round(Calculation.CalcPLuff * 1000, 0)
                TempLporFoot = Round(Calculation.CalcEFoot * 1000, 0)
            ElseIf Calculation.CodeLetter = "S" Then
                TempLuff = Round(Calculation.CalcSpinLuff * 1000, 0)
                TempLporFoot = Round(Calculation.CalcLP * 1000, 0)
            Else
                TempLuff = Round(Calculation.CalcLuff * 1000, 0)
                TempLporFoot = Round(Calculation.CalcLP * 1000, 0)
            End If
            TempArea = Calculation.CalcArea
            '  Else

        End If


        If Not IsDBNull(MyDS.Tables("LIU").Rows(0).Item("ExRate")) Then
            Calculation.ExchangeRate = MyDS.Tables("LIU").Rows(0).Item("ExRate")
            ViewState("QuoteExRate") = MyDS.Tables("LIU").Rows(0).Item("ExRate")
        Else
            Calculation.ExchangeRate = 0
            ViewState("QuoteExRate") = 0
        End If
        If Request.QueryString("Type") = 1 Then
            If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("ListRetailPrice")) Then
                Calculation.ListPrice = MyDS.Tables("LIU").Rows(Lineitem).Item("ListRetailPrice")
            Else
                Calculation.ListPrice = 0
            End If
        Else
            If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("BRP")) And Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("OptionTotal")) Then
                Calculation.ListPrice = MyDS.Tables("LIU").Rows(Lineitem).Item("BRP") + MyDS.Tables("LIU").Rows(Lineitem).Item("OptionTotal")
            Else
                Calculation.ListPrice = 0
            End If
        End If
        If MyDS.Tables("LIU").Rows(Lineitem).Item("AccessoryID") > 0 Then Calculation.AccessoryPrice = MyDS.Tables("LIU").Rows(Lineitem).Item("Price")
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("MarketCostFactor")) Then
            Calculation.MarketCF = MyDS.Tables("LIU").Rows(Lineitem).Item("MarketCostFactor")
        Else
            Calculation.MarketCF = 0
        End If
        If Not IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("SeasonalPriceFactor")) Then
            Calculation.SeasonalPF = MyDS.Tables("LIU").Rows(Lineitem).Item("SeasonalPriceFactor")
        Else
            Calculation.SeasonalPF = 0
        End If
        Dim Tempvalue As Double
        If MyDS.Tables("Quote").Rows(0).Item("BillingPriceID") = 2 Then
            If MyDS.Tables("LIU").Rows(Lineitem).Item("AccessoryID") = 0 Then
                Tempvalue = Calculation.ListMarketPrice * MyDS.Tables("LIU").Rows(Lineitem).Item("DealerExRate")
            Else
                Tempvalue = Calculation.MarketAccessRetailPriceEuro * MyDS.Tables("LIU").Rows(Lineitem).Item("DealerExRate")
            End If
        ElseIf MyDS.Tables("Quote").Rows(0).Item("BillingPriceID") = 1 Then
            If MyDS.Tables("LIU").Rows(Lineitem).Item("AccessoryID") = 0 Then
                Tempvalue = Calculation.ListSeasonalPrice * MyDS.Tables("LIU").Rows(Lineitem).Item("DealerExRate") * Calculation.MarketCF
            Else
                Tempvalue = Calculation.MarketAccessRetailPriceEuro * MyDS.Tables("LIU").Rows(Lineitem).Item("DealerExRate")
            End If
        Else
            If MyDS.Tables("LIU").Rows(Lineitem).Item("TotalOfferedPrice") > 0 Then
                Tempvalue = MyDS.Tables("LIU").Rows(Lineitem).Item("TotalOfferedPrice") '''' needs to check currency
            Else
                Tempvalue = MyDS.Tables("LIU").Rows(Lineitem).Item("Price")
            End If
            If ViewState("DealerExRate") <> ViewState("QuoteExRate") Then

                If MyDS.Tables("LIU").Rows(Lineitem).Item("AccessoryID") = 0 Then
                    Tempvalue = (MyDS.Tables("LIU").Rows(Lineitem).Item("BRP") + MyDS.Tables("LIU").Rows(Lineitem).Item("OptionTotal")) * ViewState("QuoteExRate") * Calculation.MarketCF * Calculation.SeasonalPF
                Else

                    Tempvalue = Calculation.AccessoryPrice * ViewState("QuoteExRate") * Calculation.MarketCF * Calculation.SeasonalPF
                End If
            End If
        End If
        MyCommand.CommandType = CommandType.StoredProcedure
        MyCommand.Connection = MyConnection
        MyCommand.Parameters.Clear()
        If MyDS.Tables("LIU").Rows(Lineitem).Item("AccessoryID") = 0 Then
            MyCommand.Parameters.Add(New SqlParameter("@Price", Calculation.ListSeasonalPriceCurr))
            MyCommand.Parameters.Add(New SqlParameter("@TotalPrice", Calculation.ListSeasonalPriceCurr * MyDS.Tables("LIU").Rows(Lineitem).Item("Multiple")))
            MyCommand.Parameters.Add(New SqlParameter("@TotalOfferedPrice", MyDS.Tables("LIU").Rows(Lineitem).Item("TotalOfferedPrice")))
            MyCommand.Parameters.Add(New SqlParameter("@PreDiscountPrice", Calculation.ListSeasonalPriceCurr * MyDS.Tables("LIU").Rows(Lineitem).Item("Multiple")))
            MyCommand.Parameters.Add(New SqlParameter("@MarketRetailPrice", Calculation.ListMarketPriceCurr))
            MyCommand.Parameters.Add(New SqlParameter("@MarketPriceEuro", Calculation.ListMarketPrice))
            MyCommand.Parameters.Add(New SqlParameter("@SeasonalPriceEuro", Calculation.ListSeasonalPrice))
            MyCommand.Parameters.Add(New SqlParameter("@SeasonalPriceCurr", Calculation.ListSeasonalPriceCurr))
            MyCommand.Parameters.Add(New SqlParameter("@BillingPrice", Tempvalue))
            MyCommand.Parameters.Add(New SqlParameter("@COM", Tempvalue))
        Else
            MyCommand.Parameters.Add(New SqlParameter("@Price", Calculation.MarketAccessRetailPrice))
            MyCommand.Parameters.Add(New SqlParameter("@TotalPrice", Calculation.AccessoryPrice * MyDS.Tables("LIU").Rows(Lineitem).Item("Multiple")))
            MyCommand.Parameters.Add(New SqlParameter("@TotalOfferedPrice", MyDS.Tables("LIU").Rows(Lineitem).Item("TotalOfferedPrice")))
            MyCommand.Parameters.Add(New SqlParameter("@PreDiscountPrice", Calculation.AccessoryPrice * MyDS.Tables("LIU").Rows(Lineitem).Item("Multiple")))
            MyCommand.Parameters.Add(New SqlParameter("@MarketRetailPrice", Calculation.MarketAccessRetailPrice))
            MyCommand.Parameters.Add(New SqlParameter("@MarketPriceEuro", Calculation.MarketAccessRetailPriceEuro))
            MyCommand.Parameters.Add(New SqlParameter("@SeasonalPriceEuro", Calculation.MarketAccessRetailPriceEuro))
            MyCommand.Parameters.Add(New SqlParameter("@SeasonalPriceCurr", Calculation.MarketAccessRetailPrice))
            MyCommand.Parameters.Add(New SqlParameter("@BillingPrice", Tempvalue))
        End If
        If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
        MyCommand.CommandText = "UpdateAllLineitems_SP"
    End Sub

    Sub UpdateDPIDecision(ByVal Lineitem)
        If IsDBNull(MyDS.Tables("LIU").Rows(Lineitem).Item("YarnType")) Then Exit Sub
        If MyDS.Tables("LIU").Rows(Lineitem).Item("YarnType") = "Nylon" Then Exit Sub
        If MyDS.Tables("LIU").Rows(Lineitem).Item("AccessoryID") > 0 Then Exit Sub


        Dim MaxDPIID, TargetDPI, PreviousDPIID, TempDPIID As Integer
        If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("UpdateHeadYarns").Clear()
        Catch ex As Exception
        End Try
        ' finds the Maximum DPI from Headyarns and DPI tables by checking the MaxDPI against the target DPI, there will usually be 2 values, one for lighter yarns and one for heavier yarns, and the maximum DPI for that yarn type is stored in tempmaxdpi as the value not the ID 
        MySQL = "SELECT HeadYarns_Tbl.HeadYarnsID, TargetDPI_Tbl.TargetDPI, HeadYarns_Tbl.MaxDPIID, TargetDPI_Tbl.TargetDPIID FROM HeadYarns_Tbl inner join TargetDPI_Tbl on HeadYarns_Tbl.MaxDPIID =  TargetDPI_Tbl.TargetDPIID where HeadYarns_Tbl.YarnType =@Yarntype order by  HeadYarns_Tbl.MaxDPIID"
        MyCommand.Parameters.AddWithValue("@Yarntype", MyDS.Tables("LIU").Rows(Lineitem).Item("YarnType"))
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "UpdateHeadyarns")
        If MyDS.Tables("UpdateHeadYarns").Rows.Count > 0 Then
            If Not IsDBNull(MyDS.Tables("UpdateHeadYarns").Rows(0).Item("TargetDPI")) Then
                If MyDS.Tables("UpdateHeadYarns").Rows(0).Item("TargetDPI") > MaxDPIID Then MaxDPIID = MyDS.Tables("UpdateHeadYarns").Rows(0).Item("TargetDPI")
            End If
        End If
        Try
            If Left(MyDS.Tables("LIU").Rows(Lineitem).Item("SailType"), 6) = "Code 0" Then
                TargetDPI = 2000
            Else
                TargetDPI = 6000
            End If
        Catch
        End Try


        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("UpdateDPI").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select TargetDPIID, TargetDPI from TargetDPI_Tbl where Nylon=0 order by TargetDPI"
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "UpdateDPI")
        If MyDS.Tables("UpdateDPI").Rows.Count > 0 Then
            If Not IsDBNull(MyDS.Tables("UpdateDPI").Rows(0).Item("TargetDPI")) Then Calculation.TargetDPI = MyDS.Tables("UpdateDPI").Rows(0).Item("TargetDPI")
            Calculation.InputDPI = Calculation.TargetDPI
            If MyDS.Tables("UpdateDPI").Rows(0).Item("TargetDPI") > MaxDPIID Then
                TempDPIID = Calculation.TargetDPI
                Exit Sub
            End If
            'calculation.requiredcmm comes from boat info calculation.cmm from the current reader dpi information
            If Round(Calculation.CMM(), 0) > Round(Calculation.RequiredCMM(), 0) Then
                If TargetDPI < 6001 Then
                    Calculation.TargetDPI = 6000
                    Calculation.InputDPI = 6000 'DDLDPI.SelectedItem.Text
                End If
                TempDPIID = PreviousDPIID
                Exit Sub
            End If
            TargetDPI = Calculation.TargetDPI 'not ID
            PreviousDPIID = MyDS.Tables("UpdateDPI").Rows(0).Item("TargetDPIID")

        End If
    End Sub

    Sub BindDataGrid()
        'if a non generic boat (one that has differences from the normal sizes) has been selected, an editable datagrid is produced containing details for each of the non generic boats for that boat type and model


        Dim MyDGDS = New DataSet
        Dim MyDGDA As New SqlDataAdapter
        MyCommand = New SqlCommand
        MyCommand.CommandText = FindSQL(1)
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDGDS)
        If MyDGDS.Tables(0).Rows.Count = 0 Then
            MyCommand = New SqlCommand
            MyCommand.CommandText = FindSQL(3)
            MyCommand.Connection = MyConnection
            MyDA.SelectCommand = MyCommand
            MyDA.Fill(MyDGDS)
        End If
        DGBoats.DataSource = MyDGDS
        DGBoats.DataKeyField = "BoatGenID"
        DGBoats.DataBind()
    End Sub

    Private Sub DGBoats_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DGBoats.ItemCommand
        Select Case e.CommandName
            Case "ViewDetails"
                ViewState("BoatGenID") = DGBoats.DataKeys(e.Item.ItemIndex)
                Dim myManufacturer As New Label
                myManufacturer = CType(e.Item.FindControl("DGmanufacturer"), Label)
                Dim myBoatMake As New Label
                myBoatMake = CType(e.Item.FindControl("dgBoatRange"), Label)
                Dim myBoatModel As New Label
                myBoatModel = CType(e.Item.FindControl("dgBoatModel"), Label)
                Dim myBoatName As New Label
                myBoatName = CType(e.Item.FindControl("DGBoatName"), Label)
                Dim myBoatLOA As New Label
                myBoatLOA = CType(e.Item.FindControl("dgLOA"), Label)
                Dim myBoatI As New Label
                myBoatI = CType(e.Item.FindControl("dgI"), Label)
                Dim myBoatJ As New Label
                myBoatJ = CType(e.Item.FindControl("dgJ"), Label)
                Dim myBoatP As New Label
                myBoatP = CType(e.Item.FindControl("dgP"), Label)
                Dim myBoatE As New Label
                myBoatE = CType(e.Item.FindControl("dgE"), Label)
                Dim myBoatISP As New Label
                myBoatISP = CType(e.Item.FindControl("dgISP"), Label)
                Dim myBoatSpl As New Label
                myBoatSpl = CType(e.Item.FindControl("dgSpl"), Label)
                Dim myBoatMultiplier As New Label
                myBoatMultiplier = CType(e.Item.FindControl("dgBoatMultiplier"), Label)
                Dim myBoatStyle As New Label
                myBoatStyle = CType(e.Item.FindControl("dgRM"), Label)
                Dim myBoatTypeID As New Label
                myBoatTypeID = CType(e.Item.FindControl("DGBoatTypeID"), Label)
                Dim myBoatRigGrpID As New Label
                myBoatRigGrpID = CType(e.Item.FindControl("dgBoatRigGrpID"), Label)
                If Not IsDBNull(myBoatLOA.Text) Then TBLOA.Text = myBoatLOA.Text
                If Not IsDBNull(myBoatI) Then TBI.Text = myBoatI.Text
                If Not IsDBNull(myBoatJ) Then TBJ.Text = myBoatJ.Text
                If Not IsDBNull(myBoatP) Then TBP.Text = myBoatP.Text
                If Not IsDBNull(myBoatE) Then TBE.Text = myBoatE.Text
                If Not IsDBNull(myBoatISP) Then TBISP.Text = myBoatISP.Text
                If Not IsDBNull(myBoatSpl) Then TBSPL.Text = myBoatSpl.Text
                Dim TempLOA As Double
                Dim TempI, TempJ, TempP, TempE, TempISP, TempSPL, TempBoatStyleID As Integer
                Dim TempBoatType As String
                TempBoatType = myBoatMake.Text & " - " & myBoatModel.Text
                If Not IsNumeric(myBoatLOA.Text) Then
                    TempLOA = 0
                Else
                    TempLOA = CType(myBoatLOA.Text, Double)
                End If
                If Not IsNumeric(myBoatI.Text) Then
                    TempI = 0
                Else
                    TempI = CType(myBoatI.Text, Double)
                End If
                If Not IsNumeric(myBoatJ.Text) Then
                    TempJ = 0
                Else
                    TempJ = CType(myBoatJ.Text, Double)
                End If
                If Not IsNumeric(myBoatP.Text) Then
                    TempJ = PI = 0
                Else
                    TempP = CType(myBoatP.Text, Double)
                End If
                If Not IsNumeric(myBoatE.Text) Then
                    TempE = 0
                Else
                    TempE = CType(myBoatE.Text, Double)
                End If
                If Not IsNumeric(myBoatISP.Text) Then
                    TempISP = 0
                Else
                    TempISP = CType(myBoatISP.Text, Double)
                End If
                If Not IsNumeric(myBoatSpl.Text) Then
                    TempSPL = 0
                Else
                    TempSPL = CType(myBoatSpl.Text, Double)
                End If
                Try
                    RBLBoatType.SelectedValue = myBoatTypeID.Text
                Catch ex As Exception
                    RBLBoatType.SelectedIndex = 0
                End Try
                Try
                    DDLRig.SelectedValue = myBoatRigGrpID.Text
                Catch ex As Exception
                    DDLRig.SelectedIndex = 0
                End Try
                TempBoatStyleID = myBoatTypeID.Text
                PnlDGContainer.Visible = False
                Call UpdateQuote(TempBoatType, TempLOA, TempI, TempJ, TempP, TempE, TempISP, TempSPL, TempBoatStyleID, ViewState("BoatGenID"), myBoatRigGrpID.Text)
                Calculation.Luff = TempP / 1000
                Calculation.LPorFoot = TempE / 1000
                Calculation.LoadFactorAdjuster = 1
                Calculation.CMMperDPI = 6.7
                DDLAWS.SelectedIndex = DDLAWS.Items.IndexOf(DDLAWS.Items.FindByText(Round(Calculation.MaxAWS(), 0)))
                Call DPIDecision()
                Call FillCalculations()
                Call FindCosts()
                Call FindOptions()

        End Select

    End Sub

    Sub UpdateQuote(BoatType, LOA, I, J, P, [E], ISP, SPL, BoatStyleID, BoatGenID, BoatRigGrpID)
        MyCommand.Parameters.Clear()
        MySQL = "Update Quote_Tbl set BoatType=@BoatType,  LOA=@LOA, I=@I, J=@J, P=@P, E=@E, ISP=@ISP, Spl=@Spl, BoatStyleID=@BoatStyleID, BoatGenID=@BoatGenID, BoatRigGrpID=@BoatRigGrpID, DateUpdated=@DateUpdated, BoatName=@BoatName where QuoteID=@QuoteID"
        MyCommand.Parameters.AddWithValue("@BoatType", BoatType)
        MyCommand.Parameters.AddWithValue("@LOA", LOA)
        MyCommand.Parameters.AddWithValue("@I", I)
        MyCommand.Parameters.AddWithValue("@J", J)
        MyCommand.Parameters.AddWithValue("@P", P)
        MyCommand.Parameters.AddWithValue("@E", E)
        MyCommand.Parameters.AddWithValue("@ISP", ISP)
        MyCommand.Parameters.AddWithValue("@SPL", SPL)
        MyCommand.Parameters.AddWithValue("@BoatGenID", BoatGenID)
        MyCommand.Parameters.AddWithValue("@BoatRigGrpID", BoatRigGrpID)
        MyCommand.Parameters.AddWithValue("@QuoteID", ViewState("QuoteID"))
        MyCommand.Parameters.AddWithValue("@BoatStyleID", BoatStyleID)
        MyCommand.Parameters.AddWithValue("@DateUpdated", Now())
        MyCommand.Parameters.AddWithValue("@BoatName", TBBoatName.Text)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
        MyCommand.ExecuteNonQuery()

    End Sub

    Sub FillCalculations()
        If DDLConstruction.SelectedValue = 1 Then
            Calculation.EMT = True
        Else
            Calculation.EMT = False
        End If
        Try ' this will not work when it is an accessory
            Calculation.TierID = DDLTier.SelectedValue
        Catch
            Calculation.TierID = 5
        End Try

        Try
            If Right(DDLYarnType.SelectedItem.Text, 5) = "Nylon" Then
                Calculation.Nylon = True
                ViewState("IsNylon") = True
            Else
                Calculation.Nylon = False
                ViewState("IsNylon") = False
            End If
        Catch
            Calculation.Nylon = False
            ViewState("IsNylon") = False
        End Try

        ' the calculation values are loaded in a particular order depending on what values are required from other tables
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Quote").Rows.Clear()
        Catch ex As Exception
        End Try
        ' this is finding the information from the quote stored from the aspx page.
        MySQL = "Select Q.*, Q.CustomerID as CUID,  (Select CurrencySymbol from Currency_Tbl where CurrencyID = @CurrencyID) as CurrencySymbol, CostSailType_Tbl.MaxTWS, CostSailType_Tbl.CostSailTypeID as CostSailTypeID, CostSailType_Tbl.SailTypeAddFactor, CostSailType_Tbl.Main, CostSailType_Tbl.CodeLetter, CostSailType_Tbl.Code2, CostSailType_Tbl.MaxAWSFactor, CostSailType_Tbl.MinAWSFactor, CostSailType_Tbl.MinTWS, CostSailType_Tbl.Areafactor, CostSailType_Tbl.BoatSpeedAdjuster, CostSailType_Tbl.LoadFactorAdjuster, CostSailType_Tbl.ILuffMultiplier, CostSailType_Tbl.JLPMultiplier, CostSailType_Tbl.PLuffMultiplier, CostSailType_Tbl.EFootMultiplier,  QuoteSailType_Tbl.GenSailTypeID,  QuoteSailType_Tbl.CodeSize,  QuoteSailType_Tbl.Furling,  Usage_Tbl.UsageCode, ConstructionAndrew_Tbl.ConstructionCode,  Tier_Tbl.TierCode, Adjuster_Tbl.*, Tier_Tbl.TierPriceIndicator, HeadYarns_Tbl.*, BoatType_Tbl.BoatTypeID, BoatType_Tbl.BoatTypeMultiplier, QuoteLineItem_Tbl.* from Quote_Tbl  Q  cross join CostSailType_Tbl cross join Usage_Tbl  cross join ConstructionAndrew_Tbl cross join Tier_Tbl cross join Adjuster_Tbl cross join HeadYarns_Tbl inner join QuoteSailType_Tbl on CostSailType_Tbl.CostSailTypeID = QuoteSailType_Tbl.CostSailTypeID inner join BoatType_Tbl on BoatType_Tbl.BoatTypeID = Q.BoatStyleID  inner join QuoteLineItem_Tbl on QuoteLineItem_Tbl.QuoteID = Q.QuoteID where Q.QuoteID = @QuoteID and  QuoteSailType_Tbl.QuoteSailTypeID = @QuoteSailTypeID  and Usage_Tbl.UsageTypeID=@UsageTypeID and ConstructionAndrew_Tbl.ConstructionID=@ConstructionID and Tier_Tbl.TierID = @TierID and Adjuster_Tbl.AdjusterID = 1 and HeadYarns_Tbl.YarnType=@YarnType  and Lineitem=" & ViewState("LineItem") & " order by MaxDPIID desc"
        MyCommand.Parameters.AddWithValue("@QuoteID", ViewState("QuoteID"))
        MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", DDLSailType.SelectedValue)
        MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        MyCommand.Parameters.AddWithValue("@UsageTypeID", RBRaceCruise.SelectedValue)
        Try
            MyCommand.Parameters.AddWithValue("@YarnType", DDLYarnType.SelectedItem.Text)
        Catch
            MyCommand.Parameters.AddWithValue("@YarnType", "Poly")
        End Try
        MyCommand.Parameters.AddWithValue("@CurrencyID", 13)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        ' lblmessage.Text = ViewState("QuoteID") & " " & DDLSailType.SelectedValue & " " & DDLConstruction.SelectedValue & " " & DDLTier.SelectedValue & " " & DDLRaceCruise.SelectedValue & " " & DDLYarnType.SelectedItem.Text & " " & ViewState("LineItem")
        MyDA.Fill(MyDS, "Quote")
        If MyDS.Tables("Quote").Rows.Count = 0 Then
            Exit Sub
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("LOA")) Then
            Calculation.LOA = MyDS.Tables("Quote").Rows(0).Item("LOA")
            If Calculation.LOA = 0 Then
            End If
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("I")) Then
            Calculation.I = MyDS.Tables("Quote").Rows(0).Item("I") / 1000
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("J")) Then
            Calculation.J = MyDS.Tables("Quote").Rows(0).Item("J") / 1000
            ViewState("J") = MyDS.Tables("Quote").Rows(0).Item("I")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("P")) Then
            Calculation.P = MyDS.Tables("Quote").Rows(0).Item("P") / 1000
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("Py")) Then
            Calculation.Py = MyDS.Tables("Quote").Rows(0).Item("Py") / 1000
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("E")) Then
            Calculation.ValE = MyDS.Tables("Quote").Rows(0).Item("E") / 1000
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("Ey")) Then
            Calculation.Ey = MyDS.Tables("Quote").Rows(0).Item("Ey") / 1000
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("ISP")) Then
            Calculation.ISP = MyDS.Tables("Quote").Rows(0).Item("ISP") / 1000
        Else
            Calculation.ISP = 0
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("SPL")) Then
            Calculation.SPL = MyDS.Tables("Quote").Rows(0).Item("SPL") / 1000
        Else
            Calculation.SPL = 0
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("STL")) Then
            Calculation.STL = MyDS.Tables("Quote").Rows(0).Item("STL") / 1000
        Else
            Calculation.STL = 0
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("CostSailTypeID")) Then ViewState("CostSailTypeID") = MyDS.Tables("Quote").Rows(0).Item("CostSailTypeID")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("MinTWS")) Then Calculation.MinTWS = MyDS.Tables("Quote").Rows(0).Item("MinTWS")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("MaxTWS")) Then Calculation.MaxTWS = MyDS.Tables("Quote").Rows(0).Item("MaxTWS")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("GenSailTypeID")) Then Calculation.GenSailTypeID = MyDS.Tables("Quote").Rows(0).Item("GenSailTypeID")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("MaxAWSFactor")) Then Calculation.MaxAWSFactor = MyDS.Tables("Quote").Rows(0).Item("MaxAWSFactor")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("MinAWSFactor")) Then Calculation.MinAWSFactor = MyDS.Tables("Quote").Rows(0).Item("MinAWSFactor")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("Main")) Then Calculation.Main = MyDS.Tables("Quote").Rows(0).Item("Main")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("AreaFactor")) Then
            Calculation.AreaFactor = MyDS.Tables("Quote").Rows(0).Item("AreaFactor")
            ViewState("AreaFactor") = MyDS.Tables("Quote").Rows(0).Item("AreaFactor")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("InputArea")) Then
            If TBInputArea.Enabled = False Then
                TBInputArea.Text = MyDS.Tables("Quote").Rows(0).Item("InputArea")
            Else
                If PostBackControl <> "Imgbtnarea" Then TBInputArea.Enabled = False
            End If
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("BoatSpeedAdjuster")) Then Calculation.BoatSpeedAdjuster = MyDS.Tables("Quote").Rows(0).Item("BoatSpeedAdjuster")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("LoadFactorAdjuster")) Then Calculation.LoadFactorAdjuster = MyDS.Tables("Quote").Rows(0).Item("LoadFactorAdjuster")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("ILuffMultiplier")) Then
            Calculation.FindLuff = MyDS.Tables("Quote").Rows(0).Item("ILuffMultiplier")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("EFootMultiplier")) Then
            Calculation.FindEFoot = MyDS.Tables("Quote").Rows(0).Item("EFootMultiplier")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("PLuffMultiplier")) Then
            Calculation.FindPLuff = MyDS.Tables("Quote").Rows(0).Item("PLuffMultiplier")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("JLPMultiplier")) Then
            Calculation.FindLP = MyDS.Tables("Quote").Rows(0).Item("JLPMultiplier")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("CodeLetter")) Then Calculation.CodeLetter = MyDS.Tables("Quote").Rows(0).Item("CodeLetter")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("UsageCode")) Then Calculation.UsageCode = MyDS.Tables("Quote").Rows(0).Item("UsageCode")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("ConstructionCode")) Then Calculation.ConstructionCode = MyDS.Tables("Quote").Rows(0).Item("ConstructionCode")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("CodeSize")) Then Calculation.Code2 = MyDS.Tables("Quote").Rows(0).Item("CodeSize")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("Furling")) Then Calculation.FurlCode = MyDS.Tables("Quote").Rows(0).Item("Furling")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("TierCode")) Then Calculation.TierCode = MyDS.Tables("Quote").Rows(0).Item("TierCode")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("SailTypeAddFactor")) Then Calculation.SmallSailAdjuster = MyDS.Tables("Quote").Rows(0).Item("SailTypeAddFactor")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("CMMperDPI")) Then Calculation.CMMperDPI = MyDS.Tables("Quote").Rows(0).Item("CMMperDPI")
        If (Calculation.ValE <> 0) And (Calculation.P <> 0) And (Calculation.J <> 0) And (Calculation.I <> 0) Then ' no change is made if IJPand E have not been input
            If MyDS.Tables("Quote").Rows(0).Item("Luff") = 0 Or (ViewState("GenSailTypeID") <> Calculation.GenSailTypeID) Or ViewState("FindLuff") <> Calculation.FindLuff Or ViewState("FindPLuff") <> Calculation.FindPLuff Then '  there is a check to see if the luff and lp are 0 or the sail type has been changed
                If Calculation.Main = True Then
                    TBLuff.Text = Round(Calculation.CalcPLuff * 1000, 0)
                ElseIf Calculation.CodeLetter = "S" Then
                    If Calculation.ISP <> 0 Then Calculation.I = Calculation.ISP
                    TBLuff.Text = Round(Calculation.CalcSpinLuff * 1000, 0)
                    Calculation.Luff = Calculation.CalcSpinLuff
                Else
                    TBLuff.Text = Round(Calculation.CalcLuff * 1000, 0)
                    Calculation.Luff = Calculation.CalcLuff
                End If
            Else
                TBLuff.ForeColor = Drawing.Color.Black
                Calculation.Luff = TBLuff.Text / 1000
                If PostBackControl = "TBLuff" Then
                    TBInputArea.Text = Round(Calculation.CalcArea, 1)
                    Calculation.InputArea = Calculation.CalcArea
                End If
            End If
            If MyDS.Tables("Quote").Rows(0).Item("LporFoot") = 0 Or (ViewState("GenSailTypeID") <> Calculation.GenSailTypeID) Or ViewState("FindEFoot") <> Calculation.FindEFoot Or ViewState("FindLP") <> Calculation.FindLP Then 'DDLSailType.SelectedValue <> ViewState("SailTypeID") Then
                If Calculation.Main = True Then
                    TBLporFoot.Text = Round(Calculation.CalcEFoot * 1000, 0)
                ElseIf Calculation.CodeLetter = "S" Then
                    If Calculation.STL <> 0 Then Calculation.J = Calculation.STL
                    If Calculation.SPL <> 0 Then Calculation.J = Calculation.SPL
                    TBLporFoot.Text = Round(Calculation.CalcSpinFoot * 1000, 0)
                Else
                    TBLporFoot.Text = Round(Calculation.CalcLP * 1000, 0)
                    Calculation.LPorFoot = Calculation.CalcLP
                End If
            Else
                If ViewState("J") > 0 Then ' displaying overlap percentage 
                End If
                TBLporFoot.ForeColor = Drawing.Color.Black
                Calculation.LPorFoot = TBLporFoot.Text / 1000
                If PostBackControl = "TBLporFoot" Then
                    TBInputArea.Text = Round(Calculation.CalcArea, 1)
                    Calculation.InputArea = Calculation.CalcArea
                End If
            End If
            LblSailModelCode.Text = Calculation.SailModelCode
            If DDLSailType.SelectedValue <> ViewState("SailTypeID") Then
                TBInputArea.Text = Round(Calculation.CalcArea, 1)
                If Not Calculation.Main Then
                    If ViewState("J") > 0 Then ' displaying overlap percentage
                    End If
                End If
            End If
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("ConstructionCode")) Then Calculation.ConstructionCode = MyDS.Tables("Quote").Rows(0).Item("ConstructionCode")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("BoatTypeMultiplier")) Then Calculation.BoatTypeFactor = MyDS.Tables("Quote").Rows(0).Item("BoatTypeMultiplier")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("BaseAdjuster")) Then Calculation.BaseAdjuster = MyDS.Tables("Quote").Rows(0).Item("BaseAdjuster")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("OptionAdjuster")) Then Calculation.OptionAdjuster = MyDS.Tables("Quote").Rows(0).Item("OptionAdjuster")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("HourlyRate")) Then
            ViewState("HourlyRate") = MyDS.Tables("Quote").Rows(0).Item("HourlyRate")
            Calculation.HourlyRate = MyDS.Tables("Quote").Rows(0).Item("HourlyRate")
        End If
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("CofMHoursAdjuster")) Then Calculation.CofMHoursAdjuster = MyDS.Tables("Quote").Rows(0).Item("CofMHoursAdjuster")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("HourlyCostRate")) Then ViewState("HourlyCostRate") = MyDS.Tables("Quote").Rows(0).Item("HourlyCostRate")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("ProductionTimeAdjustment")) Then Calculation.ProductionTimeAdjustment = MyDS.Tables("Quote").Rows(0).Item("ProductionTimeAdjustment")
        If Not IsDBNull(MyDS.Tables("Quote").Rows(0).Item("EMTAdjuster")) Then Calculation.EMTAdjuster = MyDS.Tables("Quote").Rows(0).Item("EMTAdjuster") 'EMTAdjuster
        Select Case MyDS.Tables("Quote").Rows(0).Item("TierPriceIndicator")
            Case "S"
                Calculation.TierAdjuster = MyDS.Tables("Quote").Rows(0).Item("STierAdjuster")
            Case "M"
                Calculation.TierAdjuster = MyDS.Tables("Quote").Rows(0).Item("MTierAdjuster")
            Case "L"
                Calculation.TierAdjuster = MyDS.Tables("Quote").Rows(0).Item("LTierAdjuster")
            Case "SY"
                Calculation.TierAdjuster = MyDS.Tables("Quote").Rows(0).Item("SYTierAdjuster")
            Case "E"
                Calculation.TierAdjuster = MyDS.Tables("Quote").Rows(0).Item("ETierAdjuster")
            Case "D"
                Calculation.TierAdjuster = MyDS.Tables("Quote").Rows(0).Item("DTierAdjuster")
        End Select

        ' if fields have been altered that require a new calculation to be made, those are called here
        Calculation.Luff = CType(TBLuff.Text, Integer) / 1000
        Calculation.LPorFoot = CType(TBLporFoot.Text, Integer) / 1000
        DDLAWS.SelectedIndex = DDLAWS.Items.IndexOf(DDLAWS.Items.FindByText(Round(Calculation.MaxAWS(), 0)))
        If TBInputArea.Text = "0" Or Not IsNumeric(TBInputArea.Text) Then
            TBInputArea.Text = Round(Calculation.CalcArea, 1)
        End If

        If ViewState("LuffInput") = True Then
            ViewState("LuffInput") = False
            LblReqdCMM.Text = Round(Calculation.RequiredCMM(), 1)
            TBInputArea.Text = Round(Calculation.CalcArea, 1)
        End If
        If ViewState("LpInput") = True Then
            ViewState("LpInput") = False
            LblReqdCMM.Text = Round(Calculation.RequiredCMM(), 1)
            TBInputArea.Text = Round(Calculation.CalcArea, 1)
        End If
        LblReqdCMM.Text = Round(Calculation.RequiredCMM(), 1)
        '''''''''''''''''''''''''''''''''''''''
        If Not IsNumeric(TBInputArea.Text) Then
            Calculation.InputArea = Calculation.CalcArea
        ElseIf CType(TBInputArea.Text, Double) = Round(Calculation.CalcArea, 1) Then
            Calculation.InputArea = Calculation.CalcArea
        Else
            Calculation.InputArea = CType(TBInputArea.Text, Double)
        End If
        If DDLConstruction.SelectedValue = 1 Then
            Call DPIDecision()
        End If
        ViewState("FindLuff") = Calculation.FindLuff
        ViewState("FindPLuff") = Calculation.FindPLuff
        ViewState("FindEFoot") = Calculation.FindEFoot
        ViewState("FindLP") = Calculation.FindLP
    End Sub

    Sub FillScreen()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("SumCheck").Rows.Clear()
        Catch
        End Try
        MySQL = "select case when sum (QuoteLineItemOption_Tbl.OptionPrice) is null then 0  else round(sum(QuoteLineItemOption_tbl.OptionPrice), 2) end as OptionPrice  from QuoteLineItemOption_Tbl   where QuoteLineItemOption_Tbl.QuoteLineItemID = @QuoteLineItemID "
        MyCommand.Parameters.AddWithValue("@QuoteLineItemID", ViewState("QuoteLineItemID"))
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        Calculation.OptionTot = MyCommand.ExecuteScalar
         If DDLConstruction.SelectedValue <> 1 Then
            LblWeight.Text = Round(Calculation.ClothWeight(), 0) & "g"
            LblWeight.Visible = True
            LblWeightText.Visible = True
        Else ' epex
            LblWeight.Text = 0
         End If
        lblLoadFactor.Text = Round(Calculation.LoadFactor, 2)

        LblBRP.Text = Round(Calculation.BaseretailPriceAdjusted, 2)
        LblOptions.Text = Calculation.OptionTotal()
        LblBoatSpeed.Text = Round(Calculation.CalcBoatSpeed, 2)
        LblReqdCMM.Text = Round(Calculation.RequiredCMM(), 0)
        If Calculation.Nylon Then
            LblMembCMM.Text = Round(Calculation.NylonCalcCMM, 0)
        Else
            LblMembCMM.Text = Round(Calculation.MembraneCMM(), 0)
        End If
        Calculation.MarketCF = 1
        Calculation.SeasonalPF = 1
        LblPrice.Text = Round(Calculation.PreAdjustPrice(), 2)

        ViewState("BaseRetailPriceCloth") = Calculation.BaseRetailPriceCloth
         LblBRPCurrency.Text = "£"
        LblOptionCurrency.Text = "£"
        LblPriceCurrency.Text = "£"
        Calculation.DealerDiscount = ViewState("DealerDiscount")
        Calculation.LineItemMultiplier = 1
 
        '  Response.Write(" YarnPriceFactor " & Calculation.YarnPriceFactor & " DPIadjuster " & Calculation.DPIadjuster & " InputArea " & Calculation.InputArea & " BaseAdjuster " & Calculation.BaseAdjuster & " SailAdjuster " & Calculation.SailAdjuster & " UsageAdjuster " & Calculation.UsageAdjuster & " marketcf " & Calculation.MarketCF & " gensailtypeID " & Calculation.GenSailTypeID & " surfacetopprice " & Calculation.SurfaceTopPrice & " surfacebotprice " & Calculation.SurfaceBottomPrice & " TierAdjuster " & Calculation.TierAdjuster & " SurfacePrice " & Calculation.SurfacePrice & " COMDPIPF " & Calculation.COMDPIPF & "<br>")
        'Response.Write(" InputArea " & Calculation.InputArea & " Small Sail Adjuster " & Calculation.SmallSailAdjuster & " HoursUsedFactor " & Calculation.HoursUsedFactor & " HourlyRate " & Calculation.HourlyRate & " TierAdjuster " & Calculation.TierAdjuster & " ClothHoursFactor " & Calculation.ClothHoursFactor & "<br>")
        '    Response.Write(" InputArea " & Calculation.InputArea & " Small Sail Adjuster " & Calculation.SmallSailAdjuster & " SailCostFactor " & Calculation.SailCostFactor & " ClothPricesSqm " & Calculation.ClothPriceSqm & " ClothAreaPrice " & Calculation.ClothAreaPrice & " BaseRetailPriceCloth " & Calculation.BaseRetailPriceCloth & " BaseretailPriceAdjusted " & Calculation.BaseretailPriceAdjusted & "<br>")
        'Response.Write(" BaseAdjuster " & Calculation.BaseAdjuster & " SailAdjuster " & Calculation.SailAdjuster & " UsAGEadjuster " & Calculation.UsageAdjuster & " Baseretailpricecloth " & Calculation.BaseRetailPriceCloth & " BRPad " & Calculation.BaseretailPriceAdjusted & " EMT " & Calculation.EMT & "<br>")
        ' Response.Write(" InputArea " & Calculation.InputArea & " COMDPIPF " & Calculation.COMDPIPF & " YarnPriceFactor " & Calculation.YarnPriceFactor & " BaseAdjuster " & Calculation.BaseAdjuster & " surfacetopprice " & Calculation.SurfaceTopPrice & " surfacebotprice " & Calculation.SurfaceBottomPrice & " EMTReefs " & Calculation.EMTReefs & " CofMHoursAdjuster " & Calculation.CofMHoursAdjuster & "<br>")
        '     Call UpdateFile()
        ' LblTotalPRice.Text = Round(Calculation.LineItemTotal, 2)
        'update options does the same thing for the options

        ''''''''''''''''''''''''''''''''''''''''''''''''''


        'Call UpdateOptions()   ' recalculates the option prices in case anything else has been changed which will affect their prices


        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        If Calculation.Nylon = True Then
            TblWeight.Visible = False
        End If
         Dim TempHourlyRate As Double
        TempHourlyRate = Calculation.HourlyRate
        If IsDBNull(ViewState("DiscountEuro")) Then ViewState("DiscountEuro") = 0
        Calculation.ClothDiscount = ViewState("DiscountEuro")
         Calculation.Sundries = FindSundry(Calculation.GenSailTypeID, Calculation.InputArea)
        Calculation.HourlyRate = TempHourlyRate

    End Sub

    Sub DPIDecision()
        'lblmessage.Text = lblmessage.Text & " DPI Decision "
        If TBLOA.Text = 0 Then Exit Sub

        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Headyarns").Rows.Clear()
        Catch ex As Exception
        End Try
        ' finds the Maximum DPI from Headyarns and DPI tables by checking the MaxDPI against the target DPI, there will usually be 2 values, one for lighter yarns and one for heavier yarns, and the maximum DPI for that yarn type is stored in tempmaxdpi as the value not the ID 
        If Page.IsPostBack Then
            MySQL = "SELECT HeadYarns_Tbl.HeadYarnsID, TargetDPI_Tbl.TargetDPI, HeadYarns_Tbl.MaxDPIID, TargetDPI_Tbl.TargetDPIID FROM HeadYarns_Tbl inner join TargetDPI_Tbl on HeadYarns_Tbl.MaxDPIID =  TargetDPI_Tbl.TargetDPIID where HeadYarns_Tbl.YarnType ='" & DDLYarnType.SelectedItem.Text & "' order by  HeadYarns_Tbl.MaxDPIID desc"
        Else
            DDLDPI.SelectedValue = 1
            Exit Sub
        End If
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "Headyarns")
        Dim TempMaxDPI, MaxDPIID As Integer
        If MyDS.Tables("Headyarns").Rows.Count = 0 Then Exit Sub
        For i = 0 To MyDS.Tables("Headyarns").Rows.Count - 1
            If Not IsDBNull(MyDS.Tables("Headyarns").Rows(i).Item("TargetDPI")) Then
                If MyDS.Tables("Headyarns").Rows(i).Item("TargetDPI") > TempMaxDPI Then TempMaxDPI = MyDS.Tables("Headyarns").Rows(i).Item("TargetDPI")
            End If
        Next
        MaxDPIID = TempMaxDPI
        Dim TempTargetDPI, TargetDPI, DPISelected, DPIIndex As Integer
        Try
            If Left(DDLYarnType.SelectedItem.Text, 6) = "Code 0" Then
                TempTargetDPI = 2000
            Else
                TempTargetDPI = 6000
            End If
        Catch
        End Try
 
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("TargetDPI").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "Select TargetDPIID, TargetDPI from TargetDPI_Tbl where Nylon=0 order by TargetDPI"
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        MyDA.Fill(MyDS, "TargetDPI")
          For j = 0 To MyDS.Tables("TargetDPI").Rows.Count - 1
            If Not IsDBNull(MyDS.Tables("TargetDPI").Rows(j).Item("TargetDPI")) Then Calculation.TargetDPI = MyDS.Tables("TargetDPI").Rows(j).Item("TargetDPI")
            Calculation.InputDPI = Calculation.TargetDPI
            If MyDS.Tables("TargetDPI").Rows(j).Item("TargetDPI") > MaxDPIID Then

                DDLDPI.SelectedIndex = DDLDPI.Items.IndexOf(DDLDPI.Items.FindByText(TargetDPI))
                ViewState("DPI") = DDLDPI.SelectedValue
                Calculation.TargetDPI = TargetDPI
                Calculation.InputDPI = TargetDPI 'DDLDPI.SelectedItem.Text
                'the next viewstate is used in case the DPI DDL is altered by the user and this is to give the previous and later 4 DPI to the calculated one
                DPIIndex = DDLDPI.SelectedIndex
                Exit Sub
            End If
            'calculation.requiredcmm comes from boat info calculation.cmm from the current reader dpi information
            Calculation.InputAWS = DDLAWS.SelectedItem.Text
            If Round(Calculation.CMM(), 0) > Round(Calculation.RequiredCMM(), 0) Then
                DDLDPI.SelectedIndex = DDLDPI.Items.IndexOf(DDLDPI.Items.FindByText(TempTargetDPI))
                ViewState("DPI") = DDLDPI.SelectedValue
                Calculation.TargetDPI = TempTargetDPI
                Calculation.InputDPI = TempTargetDPI 'DDLDPI.SelectedItem.Text
                'the next viewstate is used in case the DPI DDL is altered by the user and this is to give the previous and later 4 DPIs to the calculated one for the alteration list
                DPIIndex = DDLDPI.SelectedIndex
                If TempTargetDPI < 6001 Then
                    Try
                        DDLDPI.SelectedValue = 1
                    Catch
                    End Try
                    ViewState("DPI") = DDLDPI.SelectedValue
                    Calculation.TargetDPI = 6000
                    Calculation.InputDPI = 6000 'DDLDPI.SelectedItem.Text
                    DPIIndex = DDLDPI.SelectedIndex
                End If

                Exit Sub
            End If
            TargetDPI = Calculation.TargetDPI
            TempTargetDPI = Calculation.TargetDPI

            DDLDPI.SelectedIndex = DDLDPI.Items.IndexOf(DDLDPI.Items.FindByText(TargetDPI))
            ViewState("DPI") = DDLDPI.SelectedValue
            Calculation.TargetDPI = TargetDPI
            Calculation.InputDPI = TargetDPI 'DDLDPI.SelectedItem.Text
            'the next viewstate is used in case the DPI DDL is altered by the user and this is to give the previous and later 4 DPI to the calculated one
            DPIIndex = DDLDPI.SelectedIndex
        Next j
    End Sub

    Sub FindCosts()
        ' the cost factors are now retrieved from the database and the calculations are loaded and retrieved
        If ViewState("Accessory") = False Then
            MyCommand.Parameters.Clear()
            Try
                MyDS.Tables("AllFactors").Rows.Clear()
            Catch ex As Exception
            End Try
            MySQL = "SELECT Usage_Tbl.CostFactor, Usage_Tbl.UsageCode, Tier_Tbl.TierPriceIndicator, GenSailType_Tbl.* FROM Usage_Tbl cross join Tier_Tbl cross join GenSailType_Tbl WHERE Usage_Tbl.UsageTypeID = @UsageTypeID and Tier_Tbl.TierID=@TierID and  GenSailType_Tbl.GenSailTypeID =@GenSailTypeID"
            MyCommand.Parameters.AddWithValue("@UsageTypeID", RBRaceCruise.SelectedValue)
            MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
            MyCommand.Parameters.AddWithValue("@GenSailTypeID", Calculation.GenSailTypeID)
            MyCommand.CommandText = MySQL
            MyCommand.Connection = MyConnection
            MyDA.SelectCommand = MyCommand
            'Try
            MyDA.Fill(MyDS, "AllFactors")
            'Catch ex As Exception
            '    LblMessage.Text = ex.ToString & "<br>"
            '    LblMessage.Visible = True
            '    Exit Sub
            'End Try
            If MyDS.Tables("AllFactors").Rows.Count > 0 Then
                If Not IsDBNull(MyDS.Tables("AllFactors").Rows(0).Item("PriceMultiplier")) Then
                    ViewState("TierPriceIndicator") = MyDS.Tables("AllFactors").Rows(0).Item("TierPriceIndicator")
                    If Not IsDBNull(MyDS.Tables("AllFactors").Rows(0).Item("CostFactor")) Then Calculation.UsageAdjuster = MyDS.Tables("AllFactors").Rows(0).Item("CostFactor")
                    If Not IsDBNull(MyDS.Tables("AllFactors").Rows(0).Item("UsageCode")) Then ViewState("UsageCode") = MyDS.Tables("AllFactors").Rows(0).Item("UsageCode")
                End If
                If DDLConstruction.SelectedValue = 1 Then
                    If Not IsDBNull(MyDS.Tables("AllFactors").Rows(0).Item("EMTPriceMultiplier")) Then Calculation.SailAdjuster = MyDS.Tables("AllFactors").Rows(0).Item("EMTPriceMultiplier")
                Else
                    If Not IsDBNull(MyDS.Tables("AllFactors").Rows(0).Item("PriceMultiplier")) Then Calculation.SailAdjuster = MyDS.Tables("AllFactors").Rows(0).Item("PriceMultiplier")
                End If
            End If
            ViewState("UsageAdjuster") = Calculation.UsageAdjuster
            ViewState("SailAdjuster") = Calculation.SailAdjuster
            'the panelled laminate prices had been based on the membrane prices so the membrane prices are found if the construction is panelled laminate so the tempconstructionid was used, but it should all be changed now
            Calculation.DPIadjuster = 0
            If DDLConstruction.SelectedValue > 1 Then
                DDLDPI.Visible = False 'LblDpi.Visible = False : LblDendtx.Visible = False
                LblMembraneCMM.Visible = False : LblMembCMM.Visible = False : MCMM.Visible = False
                LblActCMM.Visible = True : LblACMM.Visible = True : FCMM.Visible = True 'IBDPI.Visible = False
                Calculation.EMT = False
                ViewState("Weight") = 0
                If DDLCloth.Items.Count > 0 Then
                    'If DDLCloth.SelectedIndex > 0 Then
                    MyCommand.Parameters.Clear()
                    Try
                        MyDS.Tables("ClothFactors").Rows.Clear()
                    Catch ex As Exception
                    End Try
                    MySQL = "SELECT  Fabric_Tbl.QuoteCost, Fabric_Tbl.DiscountEuro, Fabric_Tbl.Width, Fabric_Tbl.Ozsmsy, Fabric_Tbl.SailCostFactor, Fabric_Tbl.Gmsqm, Fabric_Tbl.CMM, ConstructionSailtype_Tbl.HoursUsedFactor FROM Fabric_Tbl cross join ConstructionSailtype_Tbl  where Fabric_Tbl.FabricID=@FabricID and ConstructionSailtype_Tbl.ConstructionID = @ConstructionID and ConstructionSailtype_Tbl.CostSailtypeID = @CostSailtypeID"

                    MyCommand.Parameters.AddWithValue("@FabricID", DDLCloth.SelectedValue)
                    MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
                    MyCommand.Parameters.AddWithValue("@CostSailtypeID", ViewState("CostSailTypeID"))
                    MyCommand.CommandText = MySQL
                    MyCommand.Connection = MyConnection
                    MyDA.SelectCommand = MyCommand
                    'Try
                    MyDA.Fill(MyDS, "ClothFactors")
                    'Catch ex As Exception
                    'LblMessage.Text = ex.ToString & "<br>"
                    'LblMessage.Visible = True
                    ' Exit Sub
                    '   End Try 'ClothWeightOz
                    '     Response.Write(MySQL & "<br>" & DDLCloth.SelectedValue & "<br>" & DDLConstruction.SelectedValue & "<br>" & ViewState("CostSailTypeID"))
                    'LblMessage.Visible = True
                    '  Exit Sub
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("Width")) Then
                        Calculation.ClothWidthFactor = MyDS.Tables("ClothFactors").Rows(0).Item("Width")
                        ViewState("ClothWidthFactor") = Calculation.ClothWidthFactor
                    End If
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("SailCostFactor")) Then
                        Calculation.SailCostFactor = MyDS.Tables("ClothFactors").Rows(0).Item("SailCostFactor")
                        ViewState("SailCostFactor") = Calculation.SailCostFactor
                    End If

                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("QuoteCost")) Then
                        Calculation.ClothPrice = MyDS.Tables("ClothFactors").Rows(0).Item("QuoteCost")
                        ViewState("ClothPrice") = Calculation.ClothPrice
                    End If
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("DiscountEuro")) Then
                        ViewState("DiscountEuro") = MyDS.Tables("ClothFactors").Rows(0).Item("DiscountEuro")
                    Else
                        ViewState("DiscountEuro") = 1
                    End If
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("Ozsmsy")) Then
                        ViewState("Weight") = Round(MyDS.Tables("ClothFactors").Rows(0).Item("Ozsmsy") * 42.83, 1)
                        LblAWeight.Text = Round(MyDS.Tables("ClothFactors").Rows(0).Item("Ozsmsy") * 42.83, 1) & "g"
                        LblAWeight.Visible = True : LblActWeight.Visible = True
                    End If
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("Gmsqm")) Then
                        If MyDS.Tables("ClothFactors").Rows(0).Item("Gmsqm") > 0 Then
                            ViewState("Weight") = MyDS.Tables("ClothFactors").Rows(0).Item("Gmsqm")
                            LblAWeight.Text = MyDS.Tables("ClothFactors").Rows(0).Item("Gmsqm") & "g"
                            LblAWeight.Visible = True : LblActWeight.Visible = True
                        End If
                    End If
                    Calculation.Weight = ViewState("Weight")
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("CMM")) Then
                        ' If MyDS.Tables(0).Rows(0).Item("Gmsqm") > 0 Then ClothWeightOz = False
                        LblACMM.Text = MyDS.Tables("ClothFactors").Rows(0).Item("CMM")
                        LblACMM.Visible = True : LblActCMM.Visible = True
                    End If
                    If Not IsDBNull(MyDS.Tables("ClothFactors").Rows(0).Item("HoursUsedFactor")) Then
                        Calculation.HoursUsedFactor = MyDS.Tables("ClothFactors").Rows(0).Item("HoursUsedFactor")
                        ViewState("HoursUsedFactor") = Calculation.HoursUsedFactor
                    End If
                    'Call DPIDecision()
                    'Response.Write(ViewState("Weight") & "<br>")
                    'Response.Write(Calculation.ClothWeight())
                    Try
                        CW.Height = Unit.Pixel(Round((ViewState("Weight") / Calculation.ClothWeight()) * 100, 0))
                        TblWeight.Visible = True
                        TblCMM.Visible = True
                        CW.Visible = True
                        RW.Visible = True
                        If (ViewState("Weight") > Calculation.ClothWeight() - (0.05 * Calculation.ClothWeight())) And (ViewState("Weight") < Calculation.ClothWeight() + (0.05 * Calculation.ClothWeight())) Then
                            CW.BackColor = Drawing.Color.SeaGreen
                        ElseIf (ViewState("Weight") > Calculation.ClothWeight() - (0.1 * Calculation.ClothWeight())) And (ViewState("Weight") < Calculation.ClothWeight() + (0.1 * Calculation.ClothWeight())) Then
                            CW.BackColor = Drawing.Color.Orange
                        ElseIf (ViewState("Weight") < Calculation.ClothWeight() - (0.1 * Calculation.ClothWeight())) Then
                            CW.BackColor = Drawing.Color.Red
                        Else
                            CW.BackColor = Drawing.Color.Orange
                        End If
                    Catch
                        CW.Visible = False
                        RW.Visible = False
                    End Try
                    Try
                        FCMM.Height = Unit.Pixel(Round((MyDS.Tables("ClothFactors").Rows(0).Item("CMM") / Calculation.RequiredCMM()) * 100, 0))
                        If (MyDS.Tables("ClothFactors").Rows(0).Item("CMM") > Calculation.RequiredCMM() - (0.1 * Calculation.RequiredCMM())) And (MyDS.Tables("ClothFactors").Rows(0).Item("CMM") < Calculation.RequiredCMM() + (0.1 * Calculation.RequiredCMM())) Then
                            FCMM.BackColor = Drawing.Color.SeaGreen
                        ElseIf (MyDS.Tables("ClothFactors").Rows(0).Item("CMM") > Calculation.RequiredCMM() - (0.15 * Calculation.RequiredCMM())) And (MyDS.Tables("ClothFactors").Rows(0).Item("CMM") < Calculation.RequiredCMM() + (0.15 * Calculation.RequiredCMM())) Then
                            FCMM.BackColor = Drawing.Color.Orange
                        ElseIf (MyDS.Tables("ClothFactors").Rows(0).Item("CMM") < Calculation.RequiredCMM() - (0.15 * Calculation.RequiredCMM())) Then
                            FCMM.BackColor = Drawing.Color.Red
                        Else
                            FCMM.BackColor = Drawing.Color.Orange
                        End If
                    Catch

                    End Try
                    'End If
                End If
                '  LblFilm.Visible = False : LblFilmType.Visible = False
                'If ViewState("IsNylon") Then
                '    Dim TempCut As Integer
                '    Try
                '        TempCut = DDLCut.SelectedIndex
                '    Catch ex As Exception
                '        TempCut = 0
                '    End Try
                '    'Call LoadCut()
                '    DDLCut.SelectedIndex = TempCut
                '    LblCut.Visible = False
                '    DDLCut.Visible = True : LblDDLCut.Visible = True
                'Else
                '    LblDDLCut.Visible = False : LblCut.Visible = True : DDLCut.Visible = False
                '    Try
                '        Select Case DDLConstruction.SelectedValue
                '            Case 2
                '                LblCut.Text = "Trioptimal"
                '            Case 5
                '                LblCut.Text = "Trioptimal"
                '            Case 3
                '                LblCut.Text = "Crosscut"
                '            Case 4
                '                LblCut.Text = "Crosscut"
                '            Case Else
                '                LblCut.Visible = False

                '        End Select
                '    Catch
                '    End Try
                'End If
                LblWeight.Text = Round(Calculation.TransportWeight(), 0) & "g"
                LblWeight.Visible = True
                LblWeightText.Visible = True
                'LblCSupText.Visible = True
                'DDLCSupplier.Visible = True
                'lblCloth.Visible = True
                'DDLCloth.Visible = True
                'IBDPI.Visible = False

            Else ' EMT values from here on
                MyCommand.Parameters.Clear()
                Try
                    MyDS.Tables("PF").Rows.Clear()
                Catch ex As Exception
                End Try
                MySQL = "SELECT PriceFactor_Tbl.PriceMultiplier, Tier_Tbl.TierPriceIndicator FROM PriceFactor_Tbl   cross join Tier_Tbl where PriceFactor_Tbl.ConstructionID = " & DDLConstruction.SelectedValue & " and PriceFactor_Tbl.GenericYarnID=" & DDLYarnType.SelectedValue & " and PriceFactor_Tbl.TierID=" & DDLTier.SelectedValue & "  and Tier_Tbl.TierID=" & DDLTier.SelectedValue
                MyCommand.CommandText = MySQL
                MyCommand.Connection = MyConnection
                MyDA.SelectCommand = MyCommand
                '     Try
                MyDA.Fill(MyDS, "PF")
                'Catch ex As Exception
                '    LblMessage.Text = ex.ToString & "<br>"
                '    LblMessage.Visible = True
                'End Try 'ClothWeightOz
                If MyDS.Tables("PF").Rows.Count > 0 Then
                    If Not IsDBNull(MyDS.Tables("PF").Rows(0).Item("PriceMultiplier")) Then
                        Calculation.YarnPriceFactor = MyDS.Tables("PF").Rows(0).Item("PriceMultiplier")
                        ViewState("TierPriceIndicator") = MyDS.Tables("PF").Rows(0).Item("TierPriceIndicator")
                    End If
                End If

                MyCommand.Parameters.Clear()
                Try
                    MyDS.Tables("TierPF").Rows.Clear()
                Catch ex As Exception
                End Try
                MySQL = "Select * from TargetDPI_Tbl where TargetDPIID=" & DDLDPI.SelectedValue
                MyCommand.CommandText = MySQL
                MyCommand.Connection = MyConnection
                MyDA.SelectCommand = MyCommand
                ' Try
                MyDA.Fill(MyDS, "TierPF")
                'Catch ex As Exception
                '    LblMessage.Text = ex.ToString & "<br>" & MySQL
                '    LblMessage.Visible = True
                '    Exit Sub
                'End Try 'ClothWeightOz

                For i = 0 To MyDS.Tables("TierPF").Rows.Count - 1
                    Select Case ViewState("TierPriceIndicator")
                        Case "S"
                            If Not IsDBNull(MyDS.Tables("TierPF").Rows(i).Item("SPriceFactor")) Then
                                Calculation.DPIadjuster = MyDS.Tables("TierPF").Rows(i).Item("SPriceFactor")
                                Calculation.COMDPIPF = MyDS.Tables("TierPF").Rows(i).Item("SCom")
                            End If
                        Case "M"
                            If Not IsDBNull(MyDS.Tables("TierPF").Rows(i).Item("MPriceFactor")) Then
                                Calculation.DPIadjuster = MyDS.Tables("TierPF").Rows(i).Item("MPriceFactor")
                                Calculation.COMDPIPF = MyDS.Tables("TierPF").Rows(i).Item("MCom")
                            End If
                        Case "L"
                            If Not IsDBNull(MyDS.Tables("TierPF").Rows(i).Item("LPriceFactor")) Then
                                Calculation.DPIadjuster = MyDS.Tables("TierPF").Rows(i).Item("LPriceFactor")
                                Calculation.COMDPIPF = MyDS.Tables("TierPF").Rows(i).Item("LCom")
                            End If
                        Case "SY"
                            If Not IsDBNull(MyDS.Tables("TierPF").Rows(i).Item("SYPriceFactor")) Then
                                Calculation.DPIadjuster = MyDS.Tables("TierPF").Rows(i).Item("SYPriceFactor")
                                Calculation.COMDPIPF = MyDS.Tables("TierPF").Rows(i).Item("SYCom")
                            End If
                        Case "E" ' Economy
                            If Not IsDBNull(MyDS.Tables("TierPF").Rows(i).Item("EPriceFactor")) Then
                                Calculation.DPIadjuster = MyDS.Tables("TierPF").Rows(i).Item("EPriceFactor")
                                Calculation.COMDPIPF = MyDS.Tables("TierPF").Rows(i).Item("ECom")
                            End If
                        Case "D" ' Code 0
                            If Not IsDBNull(MyDS.Tables("TierPF").Rows(i).Item("DPriceFactor")) Then
                                Calculation.DPIadjuster = MyDS.Tables("TierPF").Rows(i).Item("DPriceFactor")
                                Calculation.COMDPIPF = MyDS.Tables("TierPF").Rows(i).Item("DCom")
                            End If
                    End Select

                Next
                Try
                    Calculation.EMTReefs = CType(ViewState("EMTReefs"), Integer)
                Catch
                End Try
                Calculation.InputAWS = DDLAWS.SelectedItem.Text
                TblCMM.Visible = True
                LblMembraneCMM.Visible = True : LblMembCMM.Visible = True : MCMM.Visible = True
                LblActCMM.Visible = False : LblACMM.Visible = False : FCMM.Visible = False
                Try
                    MCMM.Height = Unit.Pixel(Round((Calculation.MembraneCMM() / Calculation.RequiredCMM()) * 100, 0))
                    If (Calculation.MembraneCMM() > Calculation.RequiredCMM() - (0.05 * Calculation.RequiredCMM())) And (Calculation.MembraneCMM() < Calculation.RequiredCMM() + (0.05 * Calculation.RequiredCMM())) Then
                        MCMM.BackColor = Drawing.Color.SeaGreen
                    ElseIf (Calculation.MembraneCMM() > Calculation.RequiredCMM() - (0.1 * Calculation.RequiredCMM())) And (Calculation.MembraneCMM() < Calculation.RequiredCMM() + (0.1 * Calculation.RequiredCMM())) Then
                        MCMM.BackColor = Drawing.Color.Tomato
                    Else
                        MCMM.BackColor = Drawing.Color.Red
                    End If
                Catch

                End Try
                DDLDPI.Visible = True
                'DDLTop.Visible = True : LblTop.Visible = True
                'DDLBot.Visible = True : Lblbot.Visible = True
                'LblCSupText.Visible = False
                'DDLCSupplier.Visible = False
                'lblCloth.Visible = False
                'DDLCloth.Visible = False
                'IBDPI.Visible = True
                LblWeight.Text = 0
                'Try
                '    LblFilm.Text = ViewState("FilmType")
                'Catch
                'End Try
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                ' these factors are for nylon as well as the other yarn types
                ' If DDLTop.SelectedValue > 0 And DDLBot.SelectedIndex > 0 Then 'this will find the cost of the taffetas if they have been chosen yet
                MyCommand.Parameters.Clear()
                Try
                    MyDS.Tables("SurfacePrice").Rows.Clear()
                Catch ex As Exception
                End Try
                MySQL = "SELECT SurfaceComponent_Tbl.EuroPermSq, SurfaceComponent_Tbl.Weight FROM SurfaceComponent_Tbl  WHERE SurfaceComponent_Tbl.SurfaceComponentID=" & DDLTopSurface.SelectedValue & " or SurfaceComponent_Tbl.SurfaceComponentID=" & DDLBotSurface.SelectedValue
                MyCommand.CommandText = MySQL
                MyCommand.Connection = MyConnection
                MyDA.SelectCommand = MyCommand
                ' Try
                MyDA.Fill(MyDS, "SurfacePrice")
                'Catch ex As Exception
                '    LblMessage.Text = ex.ToString & "<br>"
                '    LblMessage.Visible = True
                '    ' Exit Sub
                'End Try
                Try
                    If MyDS.Tables("SurfacePrice").Rows.Count > 1 Then
                        Calculation.SurfaceTopPrice = MyDS.Tables("SurfacePrice").Rows(0).Item("EuroPermSq")
                        Calculation.SurfaceBottomPrice = MyDS.Tables("SurfacePrice").Rows(1).Item("EuroPermSq")
                        Calculation.Weight = MyDS.Tables("SurfacePrice").Rows(0).Item("Weight") + MyDS.Tables("SurfacePrice").Rows(1).Item("Weight")
                    Else
                        Calculation.SurfaceTopPrice = MyDS.Tables("SurfacePrice").Rows(0).Item("EuroPermSq")
                        Calculation.SurfaceBottomPrice = MyDS.Tables("SurfacePrice").Rows(0).Item("EuroPermSq")
                        Calculation.Weight = MyDS.Tables("SurfacePrice").Rows(0).Item("Weight")
                    End If
                Catch ex As Exception
                End Try
                'Calculation.CMMultiplier = MyDS.Tables("SurfacePrice").Rows(0).Item("CMMultiplier")
                'Calculation.RMMultiplier = MyDS.Tables("SurfacePrice").Rows(0).Item("RMMultiplier")
                'Calculation.HeadMultiplier = MyDS.Tables("SurfacePrice").Rows(0).Item("HeadMultiplier")
                'Calculation.CMAdder = MyDS.Tables("SurfacePrice").Rows(0).Item("CMAdder")
                'Calculation.RMAdder = MyDS.Tables("SurfacePrice").Rows(0).Item("RMAdder")
                'Calculation.HeadAdder = MyDS.Tables("SurfacePrice").Rows(0).Item("HeadAdder")
                'LblWeight.Text = Round(Calculation.TransportWeight(), 0) & "g"
                'LblWeight.Visible = True
                'LblWeightText.Visible = True
            End If

            Try
                Calculation.MaxUpwBoatSpeed = LblBoatSpeed.Text
                Calculation.InputAWS = DDLAWS.SelectedItem.Text
                Calculation.InputDPI = DDLDPI.SelectedItem.Text
            Catch ex As Exception
            End Try
        Else      ' end of viewstate("AccessoryID") = false
            Calculation.AccessoryPrice = MyDS.Tables("Lineitem").Rows(0).Item("BRP")
        End If ' 
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Factors").Rows.Clear()
        Catch
        End Try

        MySQL = "SELECT  SeasonalPrice_Tbl.PriceFactor, Market_Tbl.CostFactor, (Select Currency_Tbl.ExRate from Currency_Tbl where Currency_Tbl.CurrencyID=@CurrencyID) as ExRate, (Select Currency_Tbl.ExRate from Currency_Tbl where Currency_Tbl.CurrencyID=13) as GBExRate, (Select Currency_Tbl.ExRate from Currency_Tbl where Currency_Tbl.CurrencyID=2) as DKExRate FROM  SeasonalPrice_Tbl cross join Market_Tbl WHERE  SeasonalPrice_Tbl.Weekno = @Weekno and Market_Tbl.MarketID=@MarketID"
        MyCommand.Parameters.AddWithValue("@Weekno", DatePart(DateInterval.WeekOfYear, DelDate, , FirstWeekOfYear.FirstFourDays))
        MyCommand.Parameters.AddWithValue("@MarketID", 75)
        MyCommand.Parameters.AddWithValue("@CurrencyID", 13)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        'Try
        MyDA.Fill(MyDS, "Factors")
        'Catch ex As Exception
        '    LblMessage.Text = ex.ToString & "<br>"
        '    LblMessage.Visible = True
        '    ' Exit Sub
        'End Try
        If MyDS.Tables("Factors").Rows.Count > 0 Then
            If Not IsDBNull(MyDS.Tables("Factors").Rows(0).Item("PriceFactor")) Then Calculation.SeasonalPF = MyDS.Tables("Factors").Rows(0).Item("PriceFactor")
            ViewState("SeasonalPF") = MyDS.Tables("Factors").Rows(0).Item("PriceFactor")
            Calculation.SeasonalPF = MyDS.Tables("Factors").Rows(0).Item("PriceFactor")
            Calculation.ExchangeRate = MyDS.Tables("Factors").Rows(0).Item("ExRate")
            ViewState("ExchangeRate") = MyDS.Tables("Factors").Rows(0).Item("ExRate")
            ViewState("DKKExchangeRate") = MyDS.Tables("Factors").Rows(0).Item("DKExRate")
            ViewState("GBPExchangeRate") = MyDS.Tables("Factors").Rows(0).Item("GBExRate")
            If Not IsDBNull(MyDS.Tables("Factors").Rows(0).Item("CostFactor")) Then Calculation.MarketCF = MyDS.Tables("Factors").Rows(0).Item("CostFactor")
        End If
        lblLoadFactor.Text = Round(Calculation.LoadFactor, 2)
        LblBoatSpeed.Text = Round(Calculation.CalcBoatSpeed, 2)

    End Sub

    Function FindSundry(ByVal GenSailTypeID, ByVal SSArea)
        If GenSailTypeID = 3 Then
            Return SSArea
        Else
            Return SSArea * 3
        End If
    End Function

    Sub FindOptions()
        '  the options that are available for this sail type are now found - option 44 is the specific adjustment and is not visible with the option totals but is added immediately to the BRP to avoid negative values showing in the option total
        ' the headings on the dynamic table are printed out here
        TblOptions.Rows.Clear()
        TblOptions.BorderColor = System.Drawing.Color.PowderBlue
        TblOptions.GridLines = GridLines.Both
        TblOptions.CellPadding = 4
        TblOptions.CellSpacing = 0
        TblOptions.BorderWidth = 1
        TblOptions.BorderWidth = 1

        CBCount = 0
        TblOptionCount = 1
        RowCount = 0
        'TblRow = New TableRow
        'TblCell = New TableCell
        'TblCell.HorizontalAlign = HorizontalAlign.Center
        'TblCell.BackColor = Drawing.Color.LightGray
        'TblCell.ColumnSpan = 15
        'MyLbl = New Label
        'MyLbl.BackColor = Drawing.Color.LightGray
        'MyLbl.CssClass = "fieldlabelssmall"
        'MyLbl.Text = "Options"
        'TblCell.Controls.Add(MyLbl)
        'TblRow.Controls.Add(TblCell)
        'TblOptions.Rows.Add(TblRow)
        TblRow = New TableRow
        RowCount += 1

        ' For i = 1 To 5
        MyLbl = New Label
        TblCell = New TableCell
        'If i = 2 Then
        '    TblCell.BackColor = Drawing.Color.Snow
        '    MyLbl.BackColor = Drawing.Color.Snow
        'ElseIf i = 4 Then
        '    TblCell.BackColor = Drawing.Color.Snow
        '    MyLbl.BackColor = Drawing.Color.Snow
        'Else
        TblCell.BackColor = Drawing.Color.LightGray
        MyLbl.BackColor = Drawing.Color.LightGray
        ' End If
        ' MyLbl.CssClass = "fieldlabelssmall"
        MyLbl.Text = "Options"
        TblCell.Controls.Add(MyLbl)
        TblRow.Controls.Add(TblCell)
        MyLbl = New Label
        TblCell = New TableCell
        'If i = 2 Then
        '    TblCell.BackColor = Drawing.Color.Snow
        '    MyLbl.BackColor = Drawing.Color.Snow
        'ElseIf i = 4 Then
        '    TblCell.BackColor = Drawing.Color.Snow
        '    MyLbl.BackColor = Drawing.Color.Snow
        'Else
        TblCell.BackColor = Drawing.Color.LightGray
        MyLbl.BackColor = Drawing.Color.LightGray
        'End If
        'MyLbl.CssClass = "fieldlabelssmall"
        MyLbl.Text = "PF"
        TblCell.Controls.Add(MyLbl)
        TblRow.Controls.Add(TblCell)
        MyLbl = New Label
        TblCell = New TableCell
        'If i = 2 Then
        '    TblCell.BackColor = Drawing.Color.Snow
        '    MyLbl.BackColor = Drawing.Color.Snow
        'ElseIf i = 4 Then
        '    TblCell.BackColor = Drawing.Color.Snow
        '    MyLbl.BackColor = Drawing.Color.Snow
        'Else
        TblCell.BackColor = Drawing.Color.LightGray
        MyLbl.BackColor = Drawing.Color.LightGray
        ' End If
        ' MyLbl.CssClass = "fieldlabelssmall"
        MyLbl.Text = "Cost €"
        TblCell.Controls.Add(MyLbl)
        TblRow.Controls.Add(TblCell)
        'Next i
        TblOptions.Rows.Add(TblRow)
        'MyTable.Rows.Add(TblRow)
        TblRow = New TableRow
        RowCount += 1
        'OptionCount = 0
        'this first database call loads all available options for this lineitem  into a dataset
        If DDLYarnType.Items.Count = 0 Then Exit Sub
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("Options").Rows.Clear()
        Catch
        End Try
        'If CutOnly Or SeamOnly = True Then
        '    Select Case Left(Thread.CurrentThread.CurrentUICulture.ToString, 2)
        '        Case "fr" '"fr-FR"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameFr as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.CutOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case "de" '"de-DE"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameDe as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.CutOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case "da" '"da-DK"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameDk as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.CutOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case "hu" '"hu-HU"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNamehu as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.CutOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case Else
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.CutOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '    End Select
        'ElseIf MembraneOnly Then
        '    Select Case Left(Thread.CurrentThread.CurrentUICulture.ToString, 2)
        '        Case "fr" '"fr-FR"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameFr as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & " and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 and OptionFactor_Tbl.MembraneOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"

        '        Case "de" '"de-DE"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameDe as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & " and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 and OptionFactor_Tbl.MembraneOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case "da" '"da-DK"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameDk as OptionName,  OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & " and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 and OptionFactor_Tbl.MembraneOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case "hu" '"hu-HU"
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNamehu as OptionName,  OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & " and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 and OptionFactor_Tbl.MembraneOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '        Case Else
        '            MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & " and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 and OptionFactor_Tbl.MembraneOnly = 1 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '    End Select

        'Else
        'Select Case Left(Thread.CurrentThread.CurrentUICulture.ToString, 2)
        '    Case "fr" '"fr-FR"
        '        MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameFr as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & "  and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '    Case "de" '"de-DE"
        '        MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameDe as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & "  and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '    Case "da" '"da-DK"
        '        MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNameDk as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & " and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & "  and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '    Case "hu" '"hu-HU"
        '        MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionNamehu as OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & DDLRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & "  and   OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'  and OptionFactor_Tbl.CutOnly = 0 order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '    Case Else
        MySQL = "SELECT Option_Tbl.GroupType, Option_Tbl.YesNoCB, Option_Tbl.MultiplierID, Option_Tbl.OptionID as OptionID, Option_Tbl.OptionName, OptionFactor_Tbl.OptionID, OptionFactor_Tbl.ConstructionID, OptionFactor_Tbl.TierPriceIndicator, OptionFactor_Tbl.GenericYarnID, OptionFactor_Tbl.UsageTypeID, OptionFactor_Tbl.GenSailTypeID, OptionFactor_Tbl.OptionPriceFactor FROM Option_Tbl INNER JOIN OptionFactor_Tbl ON Option_Tbl.OptionID = OptionFactor_Tbl.OptionID where  OptionFactor_Tbl.ConstructionID  = " & DDLConstruction.SelectedValue & "  and  OptionFactor_Tbl.UsageTypeID =" & RBRaceCruise.SelectedValue & "  and  OptionFactor_Tbl.GenSailTypeID =" & Calculation.GenSailTypeID & " and  OptionFactor_Tbl.TierPriceIndicator ='" & ViewState("TierPriceIndicator") & "'   order by Option_Tbl.GroupType, Option_Tbl.OptionName"
        '   End Select
        ' End If
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        'Try
        MyDA.Fill(MyDS, "Options")
        ' Catch ex As Exception
        'LblMessage.Text = ex.ToString & "<br>"
        '  LblMessage.Visible = True
        ' Exit Sub
        '  End Try
        'this next call to the database finds which options have already been written for this lineitem and stores them in a different dataset
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("RequiredOptions").Rows.Clear()
        Catch ex As Exception
        End Try
        ' MySQL = "Select * from QuoteLineItemOption_Tbl where QuoteLineItemID = " & ViewState("QuoteLineItemID")
        MySQL = "Select QuoteLineItemOption_Tbl.*, case when (select sum(OptionNumber) from QuoteLineItemOption_Tbl where (select GroupType From Option_Tbl where Option_Tbl.OptionID=QuoteLineItemOption_Tbl.OptionID)=1 and QuoteLineItemID = @QuoteLineItemID) is null then 0 else (select sum(OptionNumber) from QuoteLineItemOption_Tbl where (select GroupType From Option_Tbl where Option_Tbl.OptionID=QuoteLineItemOption_Tbl.OptionID)=1 and QuoteLineItemID = @QuoteLineItemID) end  as BattenCount, case when (select sum(OptionNumber) from QuoteLineItemOption_Tbl where (select GroupType From Option_Tbl where Option_Tbl.OptionID=QuoteLineItemOption_Tbl.OptionID)=2 and QuoteLineItemID = @QuoteLineItemID)is null then 0 else (select sum(OptionNumber) from QuoteLineItemOption_Tbl where (select GroupType From Option_Tbl where Option_Tbl.OptionID=QuoteLineItemOption_Tbl.OptionID)=2 and QuoteLineItemID = @QuoteLineItemID) end as ReefCount from QuoteLineItemOption_Tbl where QuoteLineItemID = @QuoteLineItemID"


        MyCommand.Parameters.AddWithValue("@QuoteLineItemID", ViewState("QuoteLineItemID"))
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        Try
            MyDA.Fill(MyDS, "RequiredOptions")
        Catch ex As Exception
            Exit Sub
        End Try
        If MyDS.Tables("RequiredOptions").Rows.Count > 0 Then
            ViewState("BattenCount") = MyDS.Tables("RequiredOptions").Rows(0)("BattenCount")
            ViewState("ReefCount") = MyDS.Tables("RequiredOptions").Rows(0)("ReefCount")
            ViewState("TotalOptions") = MyDS.Tables("RequiredOptions").Rows.Count
        Else
            ViewState("BattenCount") = 0
            ViewState("ReefCount") = 0
            ViewState("TotalOptions") = 0
        End If
        If MyDS.Tables("RequiredOptions").Rows.Count > 0 Then
            For opct = 0 To MyDS.Tables("RequiredOptions").Rows.Count - 1
                ArrayOptionID(opct) = MyDS.Tables("RequiredOptions").Rows(opct)("OptionID")
            Next
        End If
        Call LoadOptions()
    End Sub

    Sub LoadOptions()
        Dim Found, OptionFound As Boolean
        Calculation.EMS = False
        Calculation.OptionTot = 0
        ' A check is done between the options that are available for this sail and those that are already written for the sail in case the sail type has been changed and an option is already written which is no longer available.
        'OptionFound = False
        For opct = 0 To MyDS.Tables("RequiredOptions").Rows.Count - 1
            OptionFound = False
            If MyDS.Tables("Options").Rows.Count = 0 Then OptionFound = True
            For i = 0 To MyDS.Tables("Options").Rows.Count - 1
                If MyDS.Tables("RequiredOptions").Rows(opct)("OptionID") = MyDS.Tables("Options").Rows(i)("OptionID") Then
                    OptionFound = True

                    Exit For
                End If
            Next
        Next
        ' All the potential options are now dynamically loaded and checked to see if they are already written for this quote and if they are, either the check box is checked or the text box number is written and the cost is also displayed
        ' ViewState("MainUV") = True
        For i = 0 To MyDS.Tables("Options").Rows.Count - 1
            Calculation.SpecAdjustment = False
            '  If TblOptionCount > 5 Then ' the old row is written and a new one started
            Try
                TblOptions.Rows.Add(TblRow)
                'MyTable.Rows.Add(TblRow)
            Catch
            End Try
            TblRow = New TableRow
            RowCount += 1
            TblOptionCount = 1
            '  End If



            If MyDS.Tables("Options").Rows(i)("YesNoCB") = True Then ' these are the checkboxes
                Try
                    TblCell = New TableCell
                    MyCB = New CheckBox
                    MyCB.AutoPostBack = True
                    MyCB.ID = "MyCB" & MyDS.Tables("Options").Rows(i)("OptionID")
                    MyCB.ToolTip = MyDS.Tables("Options").Rows(i)("OptionPriceFactor")
                    MyCB.TabIndex = MyDS.Tables("Options").Rows(i)("MultiplierID")
                    MyCB.CssClass = "fieldtextsmall"
                    Found = False
                    For opct = 0 To MyDS.Tables("RequiredOptions").Rows.Count - 1
                        If MyDS.Tables("RequiredOptions").Rows(opct)("OptionID") = 63 Then ViewState("MainUV") = False
                        If MyDS.Tables("Options").Rows(i)("OptionID") = MyDS.Tables("RequiredOptions").Rows(opct)("OptionID") Then
                            MyCB.Checked = True
                            Found = True
                            Exit For
                        End If
                    Next opct
                    If Not ISEven(RowCount) Then
                        TblCell.BackColor = Drawing.Color.Gainsboro
                        MyCB.BackColor = Drawing.Color.Gainsboro
                    Else
                        TblCell.BackColor = Drawing.Color.Snow
                        MyCB.BackColor = Drawing.Color.Snow
                    End If
                    If MyDS.Tables("Options").Rows(i)("OptionID") = 55 Or MyDS.Tables("Options").Rows(i)("OptionID") = 56 Then
                        '   reef types B and C
                    Else
                        If MyDS.Tables("Options").Rows(i)("OptionID") = 63 And MyDS.Tables("Quote").Rows(0).Item("Furling") And MyDS.Tables("Quote").Rows(0).Item("Main") And MyDS.Tables("Quote").Rows(0).Item("CodeSize") Then ' UV clew for furling mains
                            MyCB.Checked = True
                            MyCB.Enabled = False
                            Found = True
                        ElseIf MyDS.Tables("Options").Rows(i)("OptionID") = 63 And MyDS.Tables("Quote").Rows(0).Item("Main") Then
                            MyCB.Checked = False
                            MyCB.Enabled = False
                            Found = False
                        End If
                        MyCB.Text = MyDS.Tables("Options").Rows(i)("OptionName")
                        TblCell.Controls.Add(MyCB)
                        TblRow.Cells.Add(TblCell)
                        TblCell = New TableCell
                        MyLbl = New Label
                        If Not ISEven(RowCount) Then
                            TblCell.BackColor = Drawing.Color.Gainsboro
                            MyLbl.BackColor = Drawing.Color.Gainsboro
                        Else
                            TblCell.BackColor = Drawing.Color.Snow
                            MyLbl.BackColor = Drawing.Color.Snow
                        End If
                        MyLbl.ID = "LblPF" & RowCount & TblOptionCount
                        MyLbl.CssClass = "fieldtextsmall"
                        If MyDS.Tables("Options").Rows(i)("OptionID") = 54 Then ' reef type A
                            MyLbl.Text = MyDS.Tables("Options").Rows(i)("OptionPriceFactor") * Calculation.ReefNumber
                            Calculation.OptionPriceFactor = MyDS.Tables("Options").Rows(i)("Optionpricefactor") * Calculation.ReefNumber
                        Else
                            MyLbl.Text = MyDS.Tables("Options").Rows(i)("OptionPriceFactor")
                            Calculation.OptionPriceFactor = MyDS.Tables("Options").Rows(i)("Optionpricefactor")
                        End If

                        Calculation.Multiplier = MyDS.Tables("Options").Rows(i)("MultiplierID")
                        TblCell.Controls.Add(MyLbl)
                        TblRow.Cells.Add(TblCell)
                        TblCell = New TableCell
                        MyLbl = New Label
                        MyLbl.CssClass = "fieldtextsmall"
                        If Found Then
                            Calculation.InputBRP = Calculation.BaseRetailPriceCloth
                            MyLbl.Text = Round(Calculation.OptionCost(), 2)
                            Calculation.OptionTot += Calculation.OptionCost()
                            If MyDS.Tables("Options").Rows(i)("OptionID") = 63 And ViewState("MainUV") And (Left(DDLSailType.SelectedItem.Text, 3) = "EMS" Or DDLSailType.SelectedValue = 7 Or DDLSailType.SelectedValue = 11 Or DDLSailType.SelectedValue = 67) = True Then
                                Call WriteQuoteLineItemOption(ViewState("QuoteLineItemID"), 63, 1, Calculation.OptionCost())
                            End If
                        End If
                        MyLbl.ID = "LblTot" & RowCount & TblOptionCount
                        If Not ISEven(RowCount) Then
                            TblCell.BackColor = Drawing.Color.Gainsboro
                            MyLbl.BackColor = Drawing.Color.Gainsboro
                        Else
                            TblCell.BackColor = Drawing.Color.Snow
                            MyLbl.BackColor = Drawing.Color.Snow
                        End If
                        TblCell.Controls.Add(MyLbl)
                        TblRow.Cells.Add(TblCell)
                        TblOptionCount += 1
                        CBCount += 1
                    End If
                    AddHandler MyCB.CheckedChanged, AddressOf mycb_checked
                Catch
                End Try
            Else ' the text boxes for battens and reefs are written
                Try
                    TblCell = New TableCell
                    MyTB = New TextBox
                    MyTB.AutoPostBack = True
                    MyTB.ID = "MyTB" & MyDS.Tables("Options").Rows(i)("OptionID")
                    MyTB.ToolTip = MyDS.Tables("Options").Rows(i)("OptionPriceFactor")
                    MyTB.TabIndex = MyDS.Tables("Options").Rows(i)("MultiplierID")
                    Found = False 'Reefs = False
                    MyTB.Text = 0
                    Calculation.EMS = False
                    For opct = 0 To MyDS.Tables("RequiredOptions").Rows.Count - 1
                        If MyDS.Tables("Options").Rows(i)("OptionID") = MyDS.Tables("RequiredOptions").Rows(opct)("OptionID") Then
                            If MyDS.Tables("Options").Rows(i)("GroupType") = 1 Then
                                Reefs = False
                                Calculation.BattenNumber = MyDS.Tables("RequiredOptions").Rows(opct)("OptionNumber")
                                Found = True
                                MyTB.Text = MyDS.Tables("RequiredOptions").Rows(opct)("OptionNumber")
                                If MyDS.Tables("RequiredOptions").Rows(opct)("OptionID") = 4 And Left(DDLSailType.SelectedItem.Text, 3) = "EMS" Then
                                    Calculation.EMS = True ' if EMS the luff is used for the price
                                End If
                                If MyDS.Tables("RequiredOptions").Rows(opct)("OptionID") = 3 And Left(DDLSailType.SelectedItem.Text, 3) = "EMS" Then ' if EMS the luff is used for the price
                                    Calculation.EMS = True
                                End If
                                Exit For
                            Else
                                Reefs = True
                                Found = True
                                If DDLConstruction.SelectedValue = 1 Then
                                    ViewState("EMTReefs") = MyDS.Tables("RequiredOptions").Rows(opct)("OptionNumber")
                                End If

                                MyTB.Text = MyDS.Tables("RequiredOptions").Rows(opct)("OptionNumber")
                                Calculation.ReefNumber = MyDS.Tables("RequiredOptions").Rows(opct)("OptionNumber")
                                Calculation.Multiplier = MyDS.Tables("Options").Rows(i)("MultiplierID")
                                Exit For
                            End If

                        End If
                    Next opct
                    If Not ISEven(RowCount) Then
                        TblCell.BackColor = Drawing.Color.Gainsboro
                        MyTB.BackColor = Drawing.Color.Gainsboro
                    Else
                        TblCell.BackColor = Drawing.Color.Snow
                        MyTB.BackColor = Drawing.Color.Snow
                    End If
                    MyTB.CssClass = "DynamicTB"
                    TblCell.Controls.Add(MyTB)
                    MyLbl = New Label
                    MyLbl.Text = "  "
                    MyLbl.CssClass = "fieldtextsmall"
                    TblCell.Controls.Add(MyLbl)
                    MyLbl = New Label
                    MyLbl.CssClass = "fieldtextsmall"
                    If Not ISEven(RowCount) Then
                        TblCell.BackColor = Drawing.Color.Gainsboro
                        MyLbl.BackColor = Drawing.Color.Gainsboro
                    Else
                        TblCell.BackColor = Drawing.Color.Snow
                        MyLbl.BackColor = Drawing.Color.Snow
                    End If
                    MyLbl.Text = MyDS.Tables("Options").Rows(i)("OptionName")
                    TblCell.Controls.Add(MyLbl) ' there are now 3 items in this cell which is now written
                    TblRow.Cells.Add(TblCell)
                    TblCell = New TableCell
                    MyLbl = New Label
                    MyLbl.CssClass = "fieldtextsmall"
                    If Not ISEven(RowCount) Then
                        TblCell.BackColor = Drawing.Color.Gainsboro
                        MyLbl.BackColor = Drawing.Color.Gainsboro
                    Else
                        TblCell.BackColor = Drawing.Color.Snow
                        MyLbl.BackColor = Drawing.Color.Snow
                    End If
                    MyLbl.Text = MyDS.Tables("Options").Rows(i)("OptionPriceFactor")
                    Calculation.OptionPriceFactor = MyDS.Tables("Options").Rows(i)("OptionPriceFactor")
                    TblCell.Controls.Add(MyLbl)
                    TblRow.Cells.Add(TblCell)
                    TblCell = New TableCell
                    MyLbl = New Label
                    MyLbl.CssClass = "fieldtextsmall"
                    If Not ISEven(RowCount) Then
                        TblCell.BackColor = Drawing.Color.Gainsboro
                        MyLbl.BackColor = Drawing.Color.Gainsboro
                    Else
                        TblCell.BackColor = Drawing.Color.Snow
                        MyLbl.BackColor = Drawing.Color.Snow
                    End If
                    If Found Then
                        If Reefs Then
                            MyLbl.Text = Round(Calculation.ReefCost, 2)
                            Calculation.OptionTot += Calculation.ReefCost
                        Else
                            MyLbl.Text = Round(Calculation.BattenCost, 2)
                            Calculation.OptionTot += Calculation.BattenCost
                        End If
                    End If
                    TblCell.Controls.Add(MyLbl)
                    TblRow.Cells.Add(TblCell)
                    ' Try
                    TblOptions.Rows.Add(TblRow)
                    'MyTable.Rows.Add(TblRow)
                    'Catch
                    'End Try
                    TblOptionCount += 1
                    CBCount += 1
                    AddHandler MyTB.TextChanged, AddressOf mycb_checked



                Catch
                    TblOptionCount += 1
                End Try
            End If
        Next
        TblOptions.Rows.Add(TblRow)
        Dim mypanel As Integer

        'lblmessage.Text = AccPOptions.Height.Value
        mypanel = AccPOptions.Height.Value
        'MyTable.Rows.Add(TblRow)
        ' PHOptions.Controls.Add(MyTable)this.Panel1.Controls.Add(new LiteralControl("</td></tr></table>");
        'If RepeatCosts = True Then
        '    LblOptions.Text = Calculation.OptionTotal()
        '    LblPreAdPr.Text = Round(Calculation.PreAdjustPrice, 2)
        '    LblSeason1.Text = Round(Calculation.SeasonalPrice1, 2)
        '    LblSeason2.Text = Round(Calculation.SeasonalPrice2, 2)
        '    LblMRCCurrency.Text = Round(Calculation.MarketRetailPrice, 2)
        '    LblMRCCurrency1.Text = Round(Calculation.MarketRetailPriceEuro, 2)
        '    LblSellPCurrency.Text = Round(Calculation.SellingPrice, 2)
        'End If

    End Sub

    Sub mycb_checked(ByVal sender As Object, ByVal e As System.EventArgs)
         Dim IsCheckbox, NoLuff As Boolean
        Dim OptionID As Integer
        If Mid(sender.ID, 3, 1) = "C" Then ' is it a batten textbox or option checkbox
            IsCheckbox = True
        Else
            IsCheckbox = False
        End If
        If PostBackControl <> "Option" And PostBackControl <> "DDLSailType" Then ' I am not sure why I have to do this but the checkboxes and textboxes of the previous page are arriving with values in them
            If IsCheckbox Then
                sender.checked = False
            Else
                sender.text = 0
            End If
            Exit Sub
        End If
        If Len(sender.id) = 6 Then 'will only be used when OptionID exceeds
            OptionID = Mid(sender.id, 5, 2)
        Else
            OptionID = Mid(sender.id, 5, 3)
        End If
        Calculation.OptionPriceFactor = CType(sender.tooltip, Double)
        Calculation.Multiplier = sender.tabindex
        If (TBLuff.Text = 0) Or (TBLporFoot.Text = 0) Then
            '  LblMessage.Text = "a value for the luff and foot must be inserted before the options can be chosen" & "<br>"
            ' LblMessage.Visible = True
            NoLuff = True
            Exit Sub
        Else
            NoLuff = False
        End If
        If IsCheckbox Then
            ' If OptionID <> 10 And OptionID <> 11 Then
            If sender.checked = True Then  'adds an option for the checkbox 
                Calculation.InputBRP = ViewState("BaseRetailPriceCloth")
                Call WriteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID, 1, Calculation.OptionCost)

            ElseIf sender.checked = False Then  'deletes an option for the checkbox
                Call DeleteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID)
            End If
            'End If
        End If
        If Not IsCheckbox Then
            Call DeleteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID)
            Calculation.EMS = False
            Try
                If sender.text > 0 Then 'adds an option for the textbox
                    If OptionID = 3 Or OptionID = 4 Or OptionID = 5 Or OptionID = 6 Or OptionID = 7 Or OptionID = 8 Then
                        If OptionID = 4 And Left(DDLSailType.SelectedItem.Text, 3) = "EMS" Then
                            Calculation.EMS = True ' EMS sails are calculated using luff not foot
                        End If
                        If OptionID = 3 And Left(DDLSailType.SelectedItem.Text, 3) = "EMS" Then
                            Calculation.EMS = True ' EMS sails are calculated using luff not foot
                        End If
                        Calculation.BattenNumber = sender.text
                        Call WriteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID, sender.text, Calculation.BattenCost)
                    Else
                        Reefs = True
                        ' Found = True
                        Calculation.ReefNumber = sender.text
                        'if optionid=54 then'reef type A 55=B 56=C
                        ViewState("EMTReefs") = sender.text

                        'If ViewState("Option44") > 0 Then
                        '    Calculation.Option44 = ViewState("Option44")
                        'Else
                        '    Calculation.Option44 = 0
                        'End If
                        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                        'Calculation.YarnPriceFactor = ViewState("YarnPriceFactor") 'is only set to 1 - 
                        'Calculation.DPIadjuster = ViewState("DPIAdjuster")
                        'Calculation.SailAdjuster = ViewState("SailAdjuster")
                        'Calculation.UsageAdjuster = ViewState("UsageAdjuster")
                        'Calculation.HoursUsedFactor = ViewState("HoursUsedFactor")
                        'Calculation.ClothPrice = ViewState("ClothPrice")
                        'Calculation.ClothWidthFactor = ViewState("ClothWidthFactor")
                        'Calculation.SailCostFactor = ViewState("SailCostFactor")
                        Call WriteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID, sender.text, Calculation.ReefCost)
                    End If
                ElseIf sender.text = 0 Then  'deletes an option for the textbox
                    Call DeleteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID)
                    If OptionID = 54 Or OptionID = 55 Or OptionID = 56 Then 'reef type A 55=B 56=C
                        ViewState("EMTReefs") = 0
                    End If
                End If
            Catch
                Call DeleteQuoteLineItemOption(ViewState("QuoteLineItemID"), OptionID)
            End Try
        End If
        ' FindBRP = True
        RepeatCosts = True
        Call FindOptions()
        '  Call MakePicture()
    End Sub

    Function ISEven(ByVal num) As Boolean
        Dim doublenum As Double
        Dim intnum As Integer
        doublenum = num
        intnum = num
        If Round(doublenum / 2, 0) = intnum / 2 Then
            Return True
        Else
            Return False
        End If
    End Function

    Sub WriteQuoteLineItemOption(ByVal QuoteLineItemID As Integer, ByVal OptionID As Integer, ByVal OptionNumber As Integer, ByVal OptionPrice As Double)
        ' the options are written to the database in this subroutine which is called for each option that has been ticked
        MyCommand.Parameters.Clear()
        'If OptionID = 10 Or OptionID = 11 Then
        '    Exit Sub
        'End If
        MySQL = "Insert into QuoteLineItemOption_Tbl (QuoteLineItemID, OptionID, OptionNumber, OptionPrice) values (@QuoteLineItemID, @OptionID, @OptionNumber, @OptionPrice)"
        MyCommand.Parameters.AddWithValue("@QuoteLineItemID", QuoteLineItemID)
        MyCommand.Parameters.AddWithValue("@OptionID", OptionID)
        MyCommand.Parameters.AddWithValue("@OptionNumber", OptionNumber)
        MyCommand.Parameters.AddWithValue("@OptionPrice", OptionPrice)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        ' Try
        MyCommand.ExecuteNonQuery()
        'Catch ex As Exception
        '    LblMessage.Text = ex.ToString & "<br>"
        '    LblMessage.Visible = True

        'End Try

        If ViewState("OEMSailListID") = 0 Then Exit Sub

        MyCommand = New SqlCommand
        MySQL = "Insert into OEMOptionList_Tbl (OEMSailListID, OptionID, OptionNumber, OptionPrice) values (@OEMSailListID, @OptionID, @OptionNumber, @OptionPrice)"
        MyCommand.Parameters.AddWithValue("@OEMSailListID", ViewState("OEMSailListID"))
        MyCommand.Parameters.AddWithValue("@OptionID", OptionID)
        MyCommand.Parameters.AddWithValue("@OptionNumber", OptionNumber)
        MyCommand.Parameters.AddWithValue("@OptionPrice", OptionPrice)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        ' Try
        MyCommand.ExecuteNonQuery()
        'Catch ex As Exception
        '    LblMessage.Text = ex.ToString & "<br>"
        '    LblMessage.Visible = True
        'End Try

    End Sub

    Sub DeleteQuoteLineItemOption(ByVal QLIID, ByVal OptionID)
        MyCommand.Parameters.Clear()
        MySQL = "Delete From QuoteLineItemOption_Tbl where QuoteLineItemID=@QuoteLineItemID and OptionID=@OptionID"
        MyCommand.Parameters.AddWithValue("@QuoteLineItemID", QLIID)
        MyCommand.Parameters.AddWithValue("@OptionID", OptionID)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        Try
            MyCommand.ExecuteNonQuery()
        Catch
        End Try

        If ViewState("OEMSailListID") = 0 Then Exit Sub

        MyCommand = New SqlCommand
        MySQL = "Delete From OEMOptionList_Tbl where OEMSailListID=@OEMSailListID and OptionID=@OptionID"
        MyCommand.Parameters.AddWithValue("@OEMSailListID", ViewState("OEMSailListID"))
        MyCommand.Parameters.AddWithValue("@OptionID", OptionID)
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        Try
            MyCommand.ExecuteNonQuery()
        Catch
        End Try

    End Sub

    Sub WriteQuote()
        If TBLOA.Text = "" Then TBLOA.Text = 0
        If TBI.Text = "" Then TBI.Text = 0
        If TBJ.Text = "" Then TBJ.Text = 0
        If TBP.Text = "" Then TBP.Text = 0
        If TBE.Text = "" Then TBE.Text = 0
        'If TBPy.Text = "" Then TBPy.Text = 0
        'If TBEy.Text = "" Then TBEy.Text = 0
        If TBISP.Text = "" Then TBISP.Text = 0
        If TBSPL.Text = "" Then TBSPL.Text = 0
        'If TBSTL.Text = "" Then TBSTL.Text = 0
        'ViewState("DeliveryDate") = DateAdd(DateInterval.WeekOfYear, 4, Now())
        ' ViewState("DelWeek") = DatePart(DateInterval.WeekOfYear, ViewState("DeliveryDate"), , FirstWeekOfYear.FirstFourDays)
        MyCommand.Parameters.Clear() ' I think this is the customer number being wrong datatype
        MySQL = "Insert into Quote_Tbl (Salesman, FirstName, LastName, BoatType, BoatName, WorksOrderNumber, LOA, DeliveryWeek, DateCreated, MarketID, I, J, P, E,  CurrencyID, BoatStyleID, Address1, Address2, Address3, PostCode, City, CountryID, DeliveryMonth, UpdateDate, Notes, Telephone, Email, Fax, VAT, OrderID, TotalValue, OfferedValue, PriceListItem, CookieID, CustomerID, LocalHostQuoteID, Fixed, FixedOfferValue, ShippingCosts, RefSalesMan, OEM,  BoatGenID, DeliveryDate, WorksOrderNumber2, StandardSailQuote, ISP, Spl, Py, Ey, PrivateCustomer, Stl, NewDeliveryAddress, DealerComment, MeasurementID, DelDate, DateCreate, DateUpdated, BoatRigGrpID) values (@Salesman, @FirstName, @LastName, @BoatType, @BoatName, @WorksOrderNumber, @LOA, @DeliveryWeek, @DateCreated, @MarketID, @I, @J, @P, @E,  @CurrencyID, @BoatStyleID, @Address1, @Address2, @Address3, @PostCode, @City, @CountryID, @DeliveryMonth, @UpdateDate, @Notes, @Telephone, @Email, @Fax, @VAT, @OrderID, @TotalValue, @OfferedValue, @PriceListItem, @CookieID, @CustomerID, @LocalHostQuoteID, @Fixed, @FixedOfferValue, @ShippingCosts, @RefSalesMan, @OEM,  @BoatGenID, @DeliveryDate, @WorksOrderNumber2, @StandardSailQuote, @ISP, @Spl, @Py, @Ey, @PrivateCustomer, @Stl, @NewDeliveryAddress, @DealerComment, @MeasurementID, @DelDate, @DateCreate, @DateUpdated, @BoatRigGrpID)  "
        MyCommand.Parameters.AddWithValue("@Salesman", "")
        MyCommand.Parameters.AddWithValue("@FirstName", "")
        MyCommand.Parameters.AddWithValue("@LastName", "")
        MyCommand.Parameters.AddWithValue("@BoatType", "")
        MyCommand.Parameters.AddWithValue("@BoatName", "")
        MyCommand.Parameters.AddWithValue("@WorksOrderNumber", "")
        MyCommand.Parameters.AddWithValue("@LOA", 0)
        MyCommand.Parameters.AddWithValue("@DeliveryWeek", DatePart(DateInterval.WeekOfYear, ViewState("DeliveryDate"), , FirstWeekOfYear.FirstFourDays))
        MyCommand.Parameters.AddWithValue("@DateCreated", Now().ToString)
        MyCommand.Parameters.AddWithValue("@MarketID", 75)
        MyCommand.Parameters.AddWithValue("@I", 0)
        MyCommand.Parameters.AddWithValue("@J", 0)
        MyCommand.Parameters.AddWithValue("@P", 0)
        MyCommand.Parameters.AddWithValue("@E", 0)
        MyCommand.Parameters.AddWithValue("@CurrencyID", 13)
        MyCommand.Parameters.AddWithValue("@BoatStyleID", 1) 'DDLBoatCat.SelectedValue)
        MyCommand.Parameters.AddWithValue("@Address1", "")
        MyCommand.Parameters.AddWithValue("@Address2", "")
        MyCommand.Parameters.AddWithValue("@Address3", "")
        MyCommand.Parameters.AddWithValue("@PostCode", "")
        MyCommand.Parameters.AddWithValue("@City", "")
        MyCommand.Parameters.AddWithValue("@CountryID", 75)
        MyCommand.Parameters.AddWithValue("@DeliveryMonth", DatePart(DateInterval.Month, ViewState("DeliveryDate"), , FirstWeekOfYear.FirstFourDays))
        MyCommand.Parameters.AddWithValue("@UpdateDate", Now())
        MyCommand.Parameters.AddWithValue("@Notes", "")
        MyCommand.Parameters.AddWithValue("@Telephone", "")
        MyCommand.Parameters.AddWithValue("@Email", "")
        MyCommand.Parameters.AddWithValue("@Fax", "")
        MyCommand.Parameters.AddWithValue("@VAT", 0.2)
        MyCommand.Parameters.AddWithValue("@OrderID", 0)
        MyCommand.Parameters.AddWithValue("@TotalValue", 0)
        MyCommand.Parameters.AddWithValue("@OfferedValue", 0)
        MyCommand.Parameters.AddWithValue("@PriceListItem", 0)
        MyCommand.Parameters.AddWithValue("@CookieID", UserID) ' for ESUK sales team with individual name
        MyCommand.Parameters.AddWithValue("@CustomerID", UserID)
        MyCommand.Parameters.AddWithValue("@LocalHostQuoteID", 0)
        MyCommand.Parameters.AddWithValue("@Fixed", 0)
        MyCommand.Parameters.AddWithValue("@FixedOfferValue", 0)
        MyCommand.Parameters.AddWithValue("@ShippingCosts", 0)
        MyCommand.Parameters.AddWithValue("@RefSalesMan", "")
        MyCommand.Parameters.AddWithValue("@OEM", 0)
        ' If ViewState("RemoveBoatID") = True Then
        'MyCommand.Parameters.AddWithValue("@BoatGenID", 0)
        ' Else
        MyCommand.Parameters.AddWithValue("@BoatGenID", 1) 'ViewState("BoatGenID"))
        ' End If
        MyCommand.Parameters.AddWithValue("@DeliveryDate", Now())
        MyCommand.Parameters.AddWithValue("@WorksOrderNumber2", "")
        MyCommand.Parameters.AddWithValue("@StandardSailQuote", 0)
        MyCommand.Parameters.AddWithValue("@ISP", 0)
        MyCommand.Parameters.AddWithValue("@Spl", 0)
        MyCommand.Parameters.AddWithValue("@Py", 0)
        MyCommand.Parameters.AddWithValue("@Ey", 0)
        MyCommand.Parameters.AddWithValue("@PrivateCustomer", 0)
        MyCommand.Parameters.AddWithValue("@Stl", 0)
        MyCommand.Parameters.AddWithValue("@NewDeliveryAddress", 0)
        MyCommand.Parameters.AddWithValue("@DealerComment", "")
        MyCommand.Parameters.AddWithValue("@MeasurementID", 1)
        MyCommand.Parameters.AddWithValue("@DelDate", Now())
        MyCommand.Parameters.AddWithValue("@DateCreate", Now())
        MyCommand.Parameters.AddWithValue("@DateUpdated", Now()) 'MembraneOnly
        MyCommand.Parameters.AddWithValue("@BoatRigGrpID", 1)
        MyCommand.CommandText = MySQL & " SELECT SCOPE_IDENTITY()"
        MyCommand.Connection = MyConnection
        ' MyCommand.Transaction = sqlTran
        ViewState("QuoteID") = MyCommand.ExecuteScalar

        MyCommand.Parameters.Clear()
        MySQL = "Insert into QuoteLineItem_Tbl (QuoteID, LineItem, QuoteSailTypeID, Luff, LporFoot, InputArea, GenericYarnID, BoatSpeed, AWS, FilmTypeID, DPIID, CurrencyID, Discount, TierID, UsageID, CreateDate, ConstructionID, Price, SailModelCode, Cut, Weight, Multiple, TotalPrice, TotalOfferedPrice, AccessoryID, PreDiscountPrice, SailNumber, SailNumberColourID, AccessoryColourID, NylonColourDetails, FixedOfferPrice, BRP, ExRate, FabricID, NewBRP, NotionalArea, AccessAttachLineItem, TopSurfaceID, BotSurfaceID, AccessoryItemID, DKKPrice, MarketPriceEuro, MarketRetailPrice, SeasonalPriceEuro, SeasonalPriceCurr, OptionTotal, BillingPrice, BillingDiscount, BillingCurrency, OEMSailListID, OriginatingOEMSailListID, COM, DesignFile, AxItem, Notes, NotArea, DeliveryDate, DepartmentID, LocaleID, AttachedToLineItem, HasAttachment, PreviousQuoteLineItemID, SailMeasurementID, OfferIncVat, ConvertToOrder) values (@QuoteID, @LineItem, @QuoteSailTypeID, @Luff, @LporFoot, @InputArea, @GenericYarnID, @BoatSpeed, @AWS, @FilmTypeID, @DPIID, @CurrencyID, @Discount, @TierID, @UsageID, @CreateDate, @ConstructionID, @Price, @SailModelCode, @Cut, @Weight,  @Multiple, @TotalPrice, @TotalOfferedPrice, @AccessoryID, @PreDiscountPrice, @SailNumber, @SailNumberColourID, @AccessoryColourID, @NylonColourDetails, @FixedOfferPrice, @BRP, @ExRate, @FabricID, @NewBRP, @NotionalArea, @AccessAttachLineItem, @TopSurfaceID, @BotSurfaceID, @AccessoryItemID, @DKKPrice, @MarketPriceEuro, @MarketRetailPrice, @SeasonalPriceEuro, @SeasonalPriceCurr, @OptionTotal, @BillingPrice, @BillingDiscount, @BillingCurrency, @OEMSailListID, @OriginatingOEMSailListID, @COM, @DesignFile, @AxItem, @Notes, @NotArea, @DeliveryDate, @DepartmentID, @LocaleID, @AttachedToLineItem, @HasAttachment, @PreviousQuoteLineItemID, @SailMeasurementID, @OfferIncVat, @ConvertToOrder)"
        Dim TempInputArea, TempBoatSpeed As Double
        ' the next lines are for conversion of decimal points to decimal commas. This just affects computers in the UK or with a browser set to en-GB
        If IsNumeric(TBInputArea.Text) Then
            TempInputArea = CType(TBInputArea.Text, Double)
        Else
            If InStr(1, TBInputArea.Text, Chr(46)) > 0 Then
                TempInputArea = CType(Replace(TBInputArea.Text, Chr(46), Chr(44)), Double)
            ElseIf InStr(1, TBInputArea.Text, Chr(44)) > 0 Then
                TempInputArea = CType(Replace(TBInputArea.Text, Chr(44), Chr(46)), Double)
            End If
        End If
        If IsNumeric(LblBoatSpeed.Text) Then
            TempBoatSpeed = CType(LblBoatSpeed.Text, Double)
        Else
            If InStr(1, LblBoatSpeed.Text, Chr(46)) > 0 Then
                TempBoatSpeed = CType(Replace(LblBoatSpeed.Text, Chr(46), Chr(44)), Double)
            ElseIf InStr(1, LblBoatSpeed.Text, Chr(44)) > 0 Then
                TempBoatSpeed = CType(Replace(LblBoatSpeed.Text, Chr(44), Chr(46)), Double)
            End If
        End If
        MyCommand.Parameters.Clear()

        MyCommand.Parameters.AddWithValue("@QuoteID", ViewState("QuoteID"))
        MyCommand.Parameters.AddWithValue("@LineItem", 1)
        MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", 1)
        MyCommand.Parameters.AddWithValue("@Luff", 0)
        MyCommand.Parameters.AddWithValue("@LporFoot", 0)
        MyCommand.Parameters.AddWithValue("@InputArea", 0)
        MyCommand.Parameters.AddWithValue("@GenericYarnID", 1)
        MyCommand.Parameters.AddWithValue("@BoatSpeed", 0)
        MyCommand.Parameters.AddWithValue("@AWS", 1)
        MyCommand.Parameters.AddWithValue("@FilmtypeID", 4)
        MyCommand.Parameters.AddWithValue("@DPIID", 1)
        MyCommand.Parameters.AddWithValue("@CurrencyID", 13)
        MyCommand.Parameters.AddWithValue("@Discount", 0)
        MyCommand.Parameters.AddWithValue("@TierID", 9)
        MyCommand.Parameters.AddWithValue("@UsageID", 1)
        MyCommand.Parameters.AddWithValue("@CreateDate", Now())
        MyCommand.Parameters.AddWithValue("@ConstructionID", 1)
        MyCommand.Parameters.AddWithValue("@Price", 0)
        MyCommand.Parameters.AddWithValue("@SailModelCode", "MC1013")
        MyCommand.Parameters.AddWithValue("@Cut", "")
        MyCommand.Parameters.AddWithValue("@Weight", 0)
        MyCommand.Parameters.AddWithValue("@Multiple", 1)
        MyCommand.Parameters.AddWithValue("@TotalPrice", 0)
        MyCommand.Parameters.AddWithValue("@BRP", 0)
        MyCommand.Parameters.AddWithValue("@FabricID", 0)
        MyCommand.Parameters.AddWithValue("@TopSurfaceID", 1)
        MyCommand.Parameters.AddWithValue("@BotSurfaceID", 1)
        MyCommand.Parameters.AddWithValue("@NotionalArea", 0)
        MyCommand.Parameters.AddWithValue("@AccessoryID", 0)
        MyCommand.Parameters.AddWithValue("@PreDiscountPrice", 0)
        MyCommand.Parameters.AddWithValue("@AccessoryColourID", 0)
        MyCommand.Parameters.AddWithValue("@AccessoryItemID", 0)
        MyCommand.Parameters.AddWithValue("@AccessAttachLineItem", 0)
        MyCommand.Parameters.AddWithValue("@BillingPrice", 0)
        MyCommand.Parameters.AddWithValue("@BillingDiscount", 0)
        MyCommand.Parameters.AddWithValue("@AxItem", "")
        MyCommand.Parameters.AddWithValue("@Notes", "")
        MyCommand.Parameters.AddWithValue("@NotArea", 0)
        MyCommand.Parameters.AddWithValue("@DeliveryDate", Now())
        MyCommand.Parameters.AddWithValue("@OptionTotal", 0)
        MyCommand.Parameters.AddWithValue("@AttachedToLineItem", 0)
        MyCommand.Parameters.AddWithValue("@HasAttachment", 0)
        MyCommand.Parameters.AddWithValue("@OfferIncVat", 0)
        MyCommand.Parameters.AddWithValue("@TotalOfferedPrice", 0)
        MyCommand.Parameters.AddWithValue("@SailNumber", "")
        MyCommand.Parameters.AddWithValue("@SailNumberColourID", 0)
        MyCommand.Parameters.AddWithValue("@NylonColourDetails", 0)
        MyCommand.Parameters.AddWithValue("@FixedOfferPrice", 0)
        MyCommand.Parameters.AddWithValue("@ExRate", 0)
        MyCommand.Parameters.AddWithValue("@NewBRP", 0)
        MyCommand.Parameters.AddWithValue("@DKKPrice", 0)
        MyCommand.Parameters.AddWithValue("@MarketPriceEuro", 0)
        MyCommand.Parameters.AddWithValue("@MarketRetailPrice", 0)
        MyCommand.Parameters.AddWithValue("@SeasonalPriceEuro", 0)
        MyCommand.Parameters.AddWithValue("@SeasonalPriceCurr", 0)
        MyCommand.Parameters.AddWithValue("@BillingCurrency", "")
        MyCommand.Parameters.AddWithValue("@OEMSailListID", 0)
        MyCommand.Parameters.AddWithValue("@OriginatingOEMSailListID", 0)
        MyCommand.Parameters.AddWithValue("@COM", 0)
        MyCommand.Parameters.AddWithValue("@DesignFile", "")
        MyCommand.Parameters.AddWithValue("@DepartmentID", 0)
        MyCommand.Parameters.AddWithValue("@LocaleID", 0)
        MyCommand.Parameters.AddWithValue("@PreviousQuoteLineitemID", 0)
        MyCommand.Parameters.AddWithValue("@SailMeasurementID", 0)
        MyCommand.Parameters.AddWithValue("@ConvertToOrder", 1)
        MyCommand.CommandText = MySQL
        '   MyCommand.Transaction = sqlTran
        MyCommand.CommandText = MySQL & " SELECT SCOPE_IDENTITY()"
        MyCommand.Connection = MyConnection
        'Dim QuoteLineItemID As Integer
        'Try
        ViewState("QuoteLineItemID") = MyCommand.ExecuteScalar
        '  Catch ex As Exception
        ' LblMessage.Text = ex.ToString & "<br>"
        'LblMessage.Visible = True
        'ViewState("MaxLineItem") -= 1
        ' ViewState("LineItem") = ViewState("MaxLineItem")
        ' Exit Sub
        ' End Try

    End Sub

    Sub MakePicture()
        'lblmessage.Text = lblmessage.Text & " MPMain=" & Calculation.GenSailTypeID
        'lblmessage.Visible = True
        '
        Dim uc As PicturePage = DirectCast(Page.LoadControl("PicturePage.ascx"), PicturePage)
        Try

            If ViewState("BattenCount") = 4 Then
                uc.CtlBattens4 = True
            ElseIf ViewState("BattenCount") = 5 Then
                uc.CtlBattens5 = True
            End If
            uc.CtlReef = ViewState("ReefCount")
            Select Case DDLTier.SelectedValue
                Case 2
                    uc.CtlTierCode = 1
                Case 3
                    uc.CtlTierCode = 2
                Case 4
                    uc.CtlTierCode = 3
                Case 5
                    uc.CtlTierCode = 2
                Case 6
                    uc.CtlTierCode = 3
                Case 9
                    uc.CtlTierCode = 1
                Case 10
                    uc.CtlTierCode = 4
                Case 19
                    uc.CtlTierCode = 5
                Case Else
                    uc.CtlTierCode = 2
            End Select
            If RBRaceCruise.SelectedValue = 2 Then
                uc.CtlRace = True
            Else
                uc.CtlRace = False
            End If
            Select Case DDLConstruction.SelectedValue
                Case 1
                    uc.CtlMembrane = True
                Case 2
                    uc.CtlTrioptimal = True
                Case 3
                    uc.CtlXCut = True
                Case 4
                    uc.CtlXCut = True
                Case 5
                    uc.CtlTrioptimal = True
            End Select
            If DDLConstruction.SelectedValue = 1 Then
                uc.CtlMembrane = True
                Select Case DDLYarnType.SelectedValue
                    Case 1
                        uc.CtlYarnColour = "Y"
                    Case 2
                        uc.CtlYarnColour = "Y"
                    Case 4
                        uc.CtlYarnColour = "W"
                    Case 5
                        uc.CtlYarnColour = "W"
                    Case 7
                        uc.CtlYarnColour = "Y"
                    Case 8
                        uc.CtlYarnColour = "Y"
                    Case 9
                        uc.CtlYarnColour = "W"
                    Case 11
                        uc.CtlYarnColour = "W"
                    Case 12
                        uc.CtlYarnColour = "W"
                    Case Else
                        uc.CtlYarnColour = "B"
                End Select
            End If
            uc.CtlSailtype = Calculation.CodeLetter
            'If ViewState("GenSailTypeID") = 1 Then
            '    uc.CtlMain = True
            '    uc.CtlHeadSail = False
            '    uc.CtlAsymetric = False
            '    uc.CtlSpinnaker = False
            'ElseIf ViewState("GenSailTypeID") = 2 Then
            '    uc.CtlMain = False
            '    uc.CtlHeadSail = True
            '    uc.CtlAsymetric = False
            '    uc.CtlSpinnaker = False
            'Else
            '    uc.CtlMain = False
            '    uc.CtlHeadSail = False
            '    uc.CtlAsymetric = False
            '    uc.CtlSpinnaker = True
            'End If
            For opct = 0 To ViewState("TotalOptions") - 1
                Select Case ArrayOptionID(opct)
                    Case 24
                        uc.CtlTrimStripes = True
                        uc.CtlTrimStripeColour = "Black"
                End Select
            Next
        Catch ex As Exception
            lblmessage.Text = ex.ToString
        End Try

        PHPicturePage.Controls.Add(uc)
         ' <uc1:PicturePage ID="PicturePage1" runat="server" />
    End Sub


    Sub FindLineItem()

        If Len(PostBackControl) = 5 Then
            ViewState("LineItem") = Right(PostBackControl, 1)
        Else
            ViewState("LineItem") = Right(PostBackControl, 2)
        End If
        'lblmessage.Text = lblmessage.Text & ViewState("LineItem")
        Call FindLineItemDetails()
        'TBInputArea.Enabled = False
    End Sub

    Sub FindLineItemDetails()
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("LineItem").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "SELECT QuoteLineItem_Tbl.*,  (select Case when AccessoryID > 0 then (select Accessory_Tbl.Accessory from Accessory_Tbl where Accessory_Tbl.AccessoryID = QuoteLineitem_Tbl.accessoryID) else '' end) as Accessory, (select Case when AccessoryID > 0 then (select Accessory_Tbl.MadeInHouse from Accessory_Tbl where Accessory_Tbl.AccessoryID = QuoteLineitem_Tbl.accessoryID) else ''end) as MadeInHouse, (select Case when AccessoryID > 0 then (select Accessory_Tbl.MultiplierID from Accessory_Tbl where Accessory_Tbl.AccessoryID = QuoteLineitem_Tbl.AccessoryID) else '' end) as MultiplierID, (select Case when AccessoryColourID > 0 then (select Colour_Tbl.Colour from Colour_Tbl where QuoteLineItem_Tbl.AccessoryColourID = Colour_Tbl.ColourID) else '' end) as Colour, (select Case when AccessoryItemID > 0 then (select AccessoryItem_Tbl.Name from AccessoryItem_Tbl where AccessoryItem_Tbl.AccessoryItemID = QuoteLineitem_Tbl.AccessoryItemID) else '' end) as AccessoryName, (select Case when AccessoryItemID > 0 then (select AccessoryItem_Tbl.Price from AccessoryItem_Tbl where AccessoryItem_Tbl.AccessoryItemID = QuoteLineitem_Tbl.AccessoryItemID) else 0 end) as AccessoryPrice, Fabric_Tbl.UMLHardwareSuppliersID, Fabric_Tbl.IsNylon,   Fabric_Tbl.FabricArchived,  Fabric_Tbl.PartCode, (select GenSailTypeID from QuoteSailType_Tbl where QuoteSailType_Tbl.QuoteSailTypeID = QuoteLineItem_Tbl.QuoteSailTypeID) as GenSailTypeID from QuoteLineItem_Tbl  left outer JOIN Fabric_Tbl ON QuoteLineItem_Tbl.FabricID = Fabric_Tbl.FabricID where  QuoteID=@QuoteID and LineItem=@LineItem"
        MyCommand.Parameters.AddWithValue("@QuoteID", ViewState("QuoteID"))
        MyCommand.Parameters.AddWithValue("@LineItem", ViewState("LineItem"))
        MyCommand.CommandText = MySQL
        MyCommand.Connection = MyConnection
        MyDA.SelectCommand = MyCommand
        'Response.Write(MySQL & "<br>" & QuoteID & "<br>" & ViewState("LineItem"))
        ' Exit Sub
        Try
            MyDA.Fill(MyDS, "LineItem")
        Catch ex As Exception
            LblMessage.Visible = True
        End Try
        Try
            ViewState("QuoteLineItemID") = MyDS.Tables("LineItem").Rows(0).Item("QuoteLineItemID")
        Catch
            lblmessage.Text = lblmessage.Text & "Can't find the LineItem"
            lblmessage.Visible = True
            Exit Sub
        End Try
        If ViewState("Accessory") = False Then
            '  DDLRaceCruise.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("UsageID")
            'If DDLRaceCruise.SelectedIndex <> 0 Then Call LoadTier()
            'Call LoadTier()
            'Try
            '    DDLTier.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("TierID")
            'Catch ex As Exception
            '    DDLTier.SelectedIndex = 0
            'End Try
            Call LoadSailType()
            Try
                DDLSailType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("QuoteSailTypeID")
                ViewState("SailTypeID") = MyDS.Tables("LineItem").Rows(0).Item("QuoteSailTypeID")
            Catch ex As Exception
                Call LoadSailType()
                DDLSailType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("QuoteSailTypeID")
                ViewState("SailTypeID") = MyDS.Tables("LineItem").Rows(0).Item("QuoteSailTypeID")
            End Try
            ViewState("GenSailTypeID") = MyDS.Tables("LineItem").Rows(0).Item("GenSailTypeID")
            Call LoadConstruction()
            DDLConstruction.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("ConstructionID")
            If DDLConstruction.SelectedValue = 1 Then
                Call LoadYarnType()
                Try
                    DDLYarnType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID")
                Catch ex As Exception
                    'Call LoadYarnType()
                    'Try
                    '    DDLYarnType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID")
                    'Catch exp As Exception
                    DDLYarnType.SelectedIndex = 0
                    'End Try
                End Try
                Call LoadSurfaces()
                Try
                    DDLTopSurface.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("TopSurfaceID")
                    Call FindBottom(DDLTopSurface.SelectedValue)
                    DDLBotSurface.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("BotSurfaceID")
                Catch
                    DDLTopSurface.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("TopSurfaceID")
                    Call FindBottom(DDLTopSurface.SelectedValue)
                    DDLBotSurface.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("BotSurfaceID")
                End Try
                DDLTopSurface.Visible = True ': LblTop.Visible = True
                DDLBotSurface.Visible = True ' : Lblbot.Visible = True
                DDLCloth.Visible = False ' : LblCSupText.Visible = False
                DDLSupplier.Visible = False ' : lblCloth.Visible = False
            Else
                DDLTopSurface.Visible = False ' : LblTop.Visible = False
                DDLBotSurface.Visible = False ' : Lblbot.Visible = False
                DDLCloth.Visible = True ' : LblCSupText.Visible = True
                DDLSupplier.Visible = True ' : lblCloth.Visible = True
                Call LoadCloth()
                Try
                    DDLCloth.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("FabricID")
                Catch ex As Exception
                    Try
                        DDLCloth.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("FabricID")
                    Catch exp As Exception
                        DDLCloth.SelectedIndex = 0
                    End Try
                End Try
                Try
                    DDLYarnType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID")
                Catch ex As Exception
                    'Call LoadYarnType()
                    'Try
                    '    DDLYarnType.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("GenericYarnID")
                    'Catch exp As Exception
                    DDLYarnType.SelectedIndex = 0
                    'End Try
                End Try
            End If
            TBLuff.Text = MyDS.Tables("LineItem").Rows(0).Item("Luff")
            TBLporFoot.Text = MyDS.Tables("LineItem").Rows(0).Item("LporFoot")
            TBInputArea.Text = MyDS.Tables("LineItem").Rows(0).Item("InputArea")
            DDLAWS.SelectedIndex = DDLAWS.Items.IndexOf(DDLAWS.Items.FindByText(MyDS.Tables("LineItem").Rows(0).Item("AWS")))
            Try
                DDLDPI.SelectedValue = MyDS.Tables("LineItem").Rows(0).Item("DPIID")
                ViewState("DPIID") = DDLDPI.SelectedItem.Text
            Catch
                DDLDPI.SelectedIndex = 0
                ViewState("DPIID") = 0
            End Try
            LblSailModelCode.Text = MyDS.Tables("LineItem").Rows(0).Item("SailModelCode")
            LblOptions.Text = MyDS.Tables("LineItem").Rows(0).Item("OptionTotal")
            LblBoatSpeed.Text = MyDS.Tables("LineItem").Rows(0).Item("BoatSpeed")
            If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("Weight")) Then
                LblWeight.Text = MyDS.Tables("LineItem").Rows(0).Item("Weight")
                ViewState("Weight") = MyDS.Tables("LineItem").Rows(0).Item("Weight")
                LblWeight.Visible = True
            End If
        End If
        lblBRP.Text = MyDS.Tables("LineItem").Rows(0).Item("BRP")
        Calculation.MarketCF = 1
        Calculation.SeasonalPF = 1
        LblPrice.Text = Round(Calculation.PreAdjustPrice(), 2)
        'LblPreAdPr.Text = MyDS.Tables("LineItem").Rows(0).Item("BRP") + MyDS.Tables("LineItem").Rows(0).Item("OptionTotal")
        'LblSeason1.Text = MyDS.Tables("LineItem").Rows(0).Item("SeasonalPriceEuro")
        'LblSeason2.Text = MyDS.Tables("LineItem").Rows(0).Item("SeasonalPriceCurr")
        'LblMRCCurrency.Text = MyDS.Tables("LineItem").Rows(0).Item("MarketRetailPrice")
        'LblMRCCurrency1.Text = MyDS.Tables("LineItem").Rows(0).Item("MarketPriceEuro")
        'LblSellPCurrency.Text = MyDS.Tables("LineItem").Rows(0).Item("Price")
        'TBMultiple.Text = MyDS.Tables("LineItem").Rows(0).Item("Multiple")
        'LblTotalPRice.Text = MyDS.Tables("LineItem").Rows(0).Item("TotalPrice")
        'TBDiscount.Text = MyDS.Tables("LineItem").Rows(0).Item("Discount")
        'If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("Notes")) Then
        '    TBLINotes.Text = MyDS.Tables("LineItem").Rows(0).Item("Notes")
        '    IBNotes.ToolTip = MyDS.Tables("LineItem").Rows(0).Item("Notes")
        '    If MyDS.Tables("LineItem").Rows(0).Item("Notes") = "" Then
        '        IBNotes.ToolTip = "Click on the pencil to add notes"
        '    End If
        'Else
        '    TBLINotes.Text = ""
        '    IBNotes.ToolTip = "Click on the pencil to add notes"
        'End If
        If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("OEMSailListID")) Then
            ViewState("OEMSailListID") = MyDS.Tables("LineItem").Rows(0).Item("OEMSailListID")
        Else
            ViewState("OEMSailListID") = 0
        End If
        'If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("FabricArchived")) Then
        '    If MyDS.Tables("LineItem").Rows(0).Item("FabricArchived") Then
        '        LblClothWarning.Visible = True
        '        LblClothWarning.Text = MyDS.Tables("LineItem").Rows(0).Item("PartCode")
        '        Select Case Left(Thread.CurrentThread.CurrentUICulture.ToString, 2)
        '            Case "de"
        '                LblClothWarning.Text = LblClothWarning.Text & " Ausgelaufen"
        '            Case "da"
        '                LblClothWarning.Text = LblClothWarning.Text & " Udgået"
        '            Case Else
        '                LblClothWarning.Text = LblClothWarning.Text & " no longer available"
        '        End Select
        '    End If
        'End If
        If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("GenSailTypeID")) Then
            Calculation.GenSailTypeID = MyDS.Tables("LineItem").Rows(0).Item("GenSailTypeID")
        Else
            Calculation.GenSailTypeID = 0
        End If
        'If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("Accessory")) Then
        '    LblAccessory.Text = MyDS.Tables("LineItem").Rows(0).Item("Accessory")
        'End If
        'If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("Colour")) Then
        '    LblColour.Text = MyDS.Tables("LineItem").Rows(0).Item("Colour")
        'End If
        'If Not IsDBNull(MyDS.Tables("LineItem").Rows(0).Item("AccessoryName")) Then
        '    LblAccDetails.Text = MyDS.Tables("LineItem").Rows(0).Item("AccessoryName")
        'End If
        Call FindButtoninUse()
        ViewState("GenSailTypeID") = Calculation.GenSailTypeID
    End Sub

    Sub BtnNotInUse()
        ' this sets the lineitem tabs to the not in use look
    End Sub

    Sub FindButtoninUse()
    End Sub

    'Sub CreateNewLineItemDetails()
    '    ViewState("MaxLineItem") += 1
    '    ViewState("LineItem") = ViewState("MaxLineItem")
    '    RBRaceCruise.SelectedIndex = 0
    '    ViewState("GenSailTypeID") = 0 : ViewState("TierPriceIndicator") = "S"
    '    Call LoadRaceCruise()
    '    'Call LoadTier()
    '    Call LoadSailType()
    '    Call LoadConstruction()
    '    Call Construction_IndexChanged()
    '    ' Call LoadYarnType()
    '    'Call LoadSurfaces()
    '    Call LoadDPI()
    '    For i = 1 To 45
    '        DDLAWS.Items.Add(i)
    '    Next
    '    DDLAWS.SelectedIndex = 0
    '    ' LblDDLCut.Visible = False : DDLCut.Visible = False
    '    TblCMM.Visible = False : TblWeight.Visible = False

    '    'Call FillCalculations()
    '    'Call FindCosts()
    '    'Call FindOptions()

    '    MySQL = "Insert into QuoteLineItem_Tbl (QuoteID, LineItem, QuoteSailTypeID, Luff, LporFoot, InputArea, GenericYarnID, BoatSpeed, AWS, FilmTypeID, DPIID, CurrencyID, Discount, TierID, UsageID, CreateDate, ConstructionID, Price, SailModelCode, Cut, Weight, Multiple, TotalPrice, TotalOfferedPrice, AccessoryID, PreDiscountPrice, SailNumber, SailNumberColourID, AccessoryColourID, NylonColourDetails, FixedOfferPrice, BRP, ExRate, FabricID, NewBRP, NotionalArea, AccessAttachLineItem, TopSurfaceID, BotSurfaceID, AccessoryItemID, DKKPrice, MarketPriceEuro, MarketRetailPrice, SeasonalPriceEuro, SeasonalPriceCurr, OptionTotal, BillingPrice, BillingDiscount, BillingCurrency, OEMSailListID, OriginatingOEMSailListID, COM, DesignFile, AxItem, Notes, NotArea, DeliveryDate, DepartmentID, LocaleID, AttachedToLineItem, HasAttachment, PreviousQuoteLineItemID, SailMeasurementID, OfferIncVat, ConvertToOrder) values (@QuoteID, @LineItem, @QuoteSailTypeID, @Luff, @LporFoot, @InputArea, @GenericYarnID, @BoatSpeed, @AWS, @FilmTypeID, @DPIID, @CurrencyID, @Discount, @TierID, @UsageID, @CreateDate, @ConstructionID, @Price, @SailModelCode, @Cut, @Weight,  @Multiple, @TotalPrice, @TotalOfferedPrice, @AccessoryID, @PreDiscountPrice, @SailNumber, @SailNumberColourID, @AccessoryColourID, @NylonColourDetails, @FixedOfferPrice, @BRP, @ExRate, @FabricID, @NewBRP, @NotionalArea, @AccessAttachLineItem, @TopSurfaceID, @BotSurfaceID, @AccessoryItemID, @DKKPrice, @MarketPriceEuro, @MarketRetailPrice, @SeasonalPriceEuro, @SeasonalPriceCurr, @OptionTotal, @BillingPrice, @BillingDiscount, @BillingCurrency, @OEMSailListID, @OriginatingOEMSailListID, @COM, @DesignFile, @AxItem, @Notes, @NotArea, @DeliveryDate, @DepartmentID, @LocaleID, @AttachedToLineItem, @HasAttachment, @PreviousQuoteLineItemID, @SailMeasurementID, @OfferIncVat, @ConvertToOrder)"
    '    Dim TempInputArea, TempBoatSpeed As Double
    '    ' the next lines are for conversion of decimal points to decimal commas. This just affects computers in the UK or with a browser set to en-GB
    '    If IsNumeric(TBInputArea.Text) Then
    '        TempInputArea = CType(TBInputArea.Text, Double)
    '    Else
    '        If InStr(1, TBInputArea.Text, Chr(46)) > 0 Then
    '            TempInputArea = CType(Replace(TBInputArea.Text, Chr(46), Chr(44)), Double)
    '        ElseIf InStr(1, TBInputArea.Text, Chr(44)) > 0 Then
    '            TempInputArea = CType(Replace(TBInputArea.Text, Chr(44), Chr(46)), Double)
    '        Else
    '            LblMessage.Text = "Area is not numeric"
    '            LblMessage.Visible = True
    '            Exit Sub
    '        End If
    '    End If
    '    If IsNumeric(LblBoatSpeed.Text) Then
    '        TempBoatSpeed = CType(LblBoatSpeed.Text, Double)
    '    Else
    '        If InStr(1, LblBoatSpeed.Text, Chr(46)) > 0 Then
    '            TempBoatSpeed = CType(Replace(LblBoatSpeed.Text, Chr(46), Chr(44)), Double)
    '        ElseIf InStr(1, LblBoatSpeed.Text, Chr(44)) > 0 Then
    '            TempBoatSpeed = CType(Replace(LblBoatSpeed.Text, Chr(44), Chr(46)), Double)
    '        Else
    '            LblMessage.Text = "Area is not numeric"
    '            LblMessage.Visible = True
    '            Exit Sub
    '        End If
    '    End If
    '    MyCommand.Parameters.Clear()
    '    MyCommand.Parameters.AddWithValue("@QuoteID", ViewState("QuoteID"))
    '    MyCommand.Parameters.AddWithValue("@LineItem", ViewState("MaxLineItem"))
    '    MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", 1)
    '    MyCommand.Parameters.AddWithValue("@Luff", 0)
    '    MyCommand.Parameters.AddWithValue("@LporFoot", 0)
    '    MyCommand.Parameters.AddWithValue("@InputArea", 0)
    '    MyCommand.Parameters.AddWithValue("@GenericYarnID", 1)
    '    MyCommand.Parameters.AddWithValue("@BoatSpeed", 0)
    '    MyCommand.Parameters.AddWithValue("@AWS", 1)
    '    MyCommand.Parameters.AddWithValue("@FilmtypeID", 4)
    '    MyCommand.Parameters.AddWithValue("@DPIID", 1)
    '    MyCommand.Parameters.AddWithValue("@CurrencyID", 13)
    '    MyCommand.Parameters.AddWithValue("@Discount", 0)
    '    MyCommand.Parameters.AddWithValue("@TierID", 9)
    '    MyCommand.Parameters.AddWithValue("@UsageID", 1)
    '    MyCommand.Parameters.AddWithValue("@CreateDate", Now())
    '    MyCommand.Parameters.AddWithValue("@ConstructionID", 1)
    '    MyCommand.Parameters.AddWithValue("@Price", 0)
    '    MyCommand.Parameters.AddWithValue("@SailModelCode", 0)
    '    MyCommand.Parameters.AddWithValue("@Cut", "")
    '    MyCommand.Parameters.AddWithValue("@Weight", 0)
    '    MyCommand.Parameters.AddWithValue("@Multiple", 1)
    '    MyCommand.Parameters.AddWithValue("@TotalPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@BRP", 0)
    '    MyCommand.Parameters.AddWithValue("@FabricID", 0)
    '    MyCommand.Parameters.AddWithValue("@TopSurfaceID", 1)
    '    MyCommand.Parameters.AddWithValue("@BotSurfaceID", 1)
    '    MyCommand.Parameters.AddWithValue("@NotionalArea", 0)
    '    MyCommand.Parameters.AddWithValue("@AccessoryID", 0)
    '    MyCommand.Parameters.AddWithValue("@PreDiscountPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@AccessoryColourID", 0)
    '    MyCommand.Parameters.AddWithValue("@AccessoryItemID", 0)
    '    MyCommand.Parameters.AddWithValue("@AccessAttachLineItem", 0)
    '    MyCommand.Parameters.AddWithValue("@BillingPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@BillingDiscount", 0)
    '    MyCommand.Parameters.AddWithValue("@AxItem", "")
    '    MyCommand.Parameters.AddWithValue("@Notes", "")
    '    MyCommand.Parameters.AddWithValue("@NotArea", 0)
    '    MyCommand.Parameters.AddWithValue("@DeliveryDate", Now())
    '    MyCommand.Parameters.AddWithValue("@OptionTotal", 0)
    '    MyCommand.Parameters.AddWithValue("@AttachedToLineItem", 0)
    '    MyCommand.Parameters.AddWithValue("@HasAttachment", 0)
    '    MyCommand.Parameters.AddWithValue("@OfferIncVat", 0)
    '    MyCommand.Parameters.AddWithValue("@TotalOfferedPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@SailNumber", "")
    '    MyCommand.Parameters.AddWithValue("@SailNumberColourID", 0)
    '    MyCommand.Parameters.AddWithValue("@NylonColourDetails", 0)
    '    MyCommand.Parameters.AddWithValue("@FixedOfferPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@ExRate", 0)
    '    MyCommand.Parameters.AddWithValue("@NewBRP", 0)
    '    MyCommand.Parameters.AddWithValue("@DKKPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@MarketPriceEuro", 0)
    '    MyCommand.Parameters.AddWithValue("@MarketRetailPrice", 0)
    '    MyCommand.Parameters.AddWithValue("@SeasonalPriceEuro", 0)
    '    MyCommand.Parameters.AddWithValue("@SeasonalPriceCurr", 0)
    '    MyCommand.Parameters.AddWithValue("@BillingCurrency", "")
    '    MyCommand.Parameters.AddWithValue("@OEMSailListID", 0)
    '    MyCommand.Parameters.AddWithValue("@OriginatingOEMSailListID", 0)
    '    MyCommand.Parameters.AddWithValue("@COM", 0)
    '    MyCommand.Parameters.AddWithValue("@DesignFile", "")
    '    MyCommand.Parameters.AddWithValue("@DepartmentID", 0)
    '    MyCommand.Parameters.AddWithValue("@LocaleID", 0)
    '    MyCommand.Parameters.AddWithValue("@PreviousQuoteLineitemID", 0)
    '    MyCommand.Parameters.AddWithValue("@SailMeasurementID", 0)
    '    MyCommand.Parameters.AddWithValue("@ConvertToOrder", 1)
    '    MyCommand.CommandText = MySQL
    '    '   MyCommand.Transaction = sqlTran
    '    MyCommand.CommandText = MySQL & " SELECT SCOPE_IDENTITY()"
    '    MyCommand.Connection = MyConnection
    '    'Dim QuoteLineItemID As Integer
    '    'Try
    '    ViewState("QuoteLineItemID") = MyCommand.ExecuteScalar
    '    '  ViewState("TierPriceIndicator") = TierPriceIndicator

    '    Call FindButtoninUse()
    'End Sub



    Sub UpdateFile()
        'MyCommand = New SqlCommand
        '  lblmessage.Text = lblmessage.Text & " " & " updatefile =" & TBLuff.Text
        Dim TempDiscount, TempPrice, TempOfferPrice As Double
        Dim TempSailCode, TempFabricID As Integer
        Dim tempcut As String
        TempPrice = Calculation.SellingPrice()
        If DDLSailType.SelectedIndex = 0 Then
            TempSailCode = 1
        Else
            Try
                TempSailCode = DDLSailType.SelectedValue
            Catch
            End Try
        End If
        If DDLConstruction.SelectedValue > 1 Then
            Try
                TempFabricID = DDLCloth.SelectedValue
            Catch
                TempFabricID = 0
            End Try
        End If
        '   If Not IsNumeric(TBDiscount.Text) Then
        TempDiscount = CType(0, Double)
        TempOfferPrice = CType(0, Double)
        '   End If
        '   If TBDiscount.Text = 0 Then
        ' TempDiscount = CType(0, Double)
        TempOfferPrice = CType(0, Double)
        '  End If
        'If ViewState("Accessory") = True Then
        '    TempPrice = Calculation.SellingAccessPrice
        '    If TBDiscount.Text = 0 Then
        '        If Not IsNumeric(Calculation.SellingAccessPrice) Then
        '            TempOfferPrice = Calculation.SellingAccessPrice
        '        Else
        '            TempOfferPrice = 0
        '        End If
        '    Else
        '        '   If ViewState("TotalofferedPrice") = 0 Then
        '        'TempOfferPrice = Calculation.SellingPrice
        '        '   Else
        '        TempOfferPrice = ViewState("TotalofferedPrice")
        '        'End If
        '    End If

        '    'TempOfferPrice = Calculation.SellingAccessPrice
        '    TempDiscount = Calculation.Discount
        'Else
        'If TBDiscount.Text = 0 Then
        '    If IsNumeric(Calculation.SellingPrice) Then
        '        TempOfferPrice = Calculation.SellingPrice
        '    Else
        '        TempOfferPrice = 0
        '    End If
        'Else
        'If ViewState("TotalofferedPrice") = 0 Then
        '     TempOfferPrice = Calculation.SellingPrice
        ' Else
        TempOfferPrice = ViewState("TotalofferedPrice")
        ' End If
        ' End If
        TempDiscount = Calculation.Discount
        TempPrice = Calculation.SellingPrice()
        'End If
        '  End If
        '   Calculation.UsageCode = Left(DDLRaceCruise.SelectedItem.Text, 1)
        Calculation.LineItemMultiplier = 1 'TBMultiple.Text
        If DDLConstruction.SelectedValue = 1 Then ViewState("Weight") = 0
        'If DDLCut.Visible = True Then
        '    Try
        '        tempcut = DDLCut.SelectedItem.Text
        '    Catch
        tempcut = ""
        ' End Try
        'Else
        'tempcut = LblCut.Text
        'End If
        Dim MyDDLTop, MyDDLBot As Integer
        Try
            MyDDLTop = DDLTopSurface.SelectedValue
        Catch
            MyDDLTop = 0
        End Try
        Try
            MyDDLBot = DDLBotSurface.SelectedValue
        Catch
            MyDDLBot = 0
        End Try
        Dim TempBillPrice, TempDisc As Double
        'Dim TempCurr As String
        'If Not IsDBNull(ViewState("BillingCurrency")) Then
        '    TempCurr = ViewState("BillingCurrency")
        'Else
        '    TempCurr = ""
        'End If
        If IsNumeric(ViewState("DealerDiscount")) Then
            TempDisc = CType(ViewState("DealerDiscount"), Double)
        Else
            TempDisc = 0
        End If
        Calculation.ListPrice = Calculation.BaseretailPriceAdjusted + Calculation.OptionTotal
        'If ViewState("Accessory") <> True Then

        '    Select Case MyDS.Tables("Quote").Rows(0).Item("BillingPriceID")
        '        Case 1
        TempBillPrice = Calculation.ListDealerSeasonlMktPrice
        '        Case 2
        'TempBillPrice = Calculation.ListDealermarketPrice
        '        Case 3
        '' If ViewState("DealerMarket") = 22 Then
        'TempBillPrice = Calculation.SellingPrice
        ''  Else
        '' TempBillPrice = Calculation.ListDealerSeasonlMktPrice - (Calculation.ListDealerSeasonlMktPrice * Calculation.Discount / 100)
        '' End If
        '    End Select
        ' End If
        '    Response.Write(" calculation.ClothAreaPrice() " & Calculation.ClothAreaPrice() & " calculation.ClothHoursFactor() " & Calculation.ClothHoursFactor() & " calculation.CutOnlyPerc " & Calculation.CutOnlyPerc & " calculation.BaseAdjuster " & Calculation.BaseAdjuster & " calculation.SailAdjuster " & Calculation.SailAdjuster & " calculation.UsageAdjuster " & Calculation.UsageAdjuster & " calculation.DealerExchangeRate " & Calculation.DealerExchangeRate)
        'If CutOnly Or MembraneOnly Or SeamOnly Then
        '    TempBillPrice = CType(LblDealerPrice.Text, Double)
        'End If

        'there has been as error of 'none' appearing with both top and bottom films having been selected so this is a final check and correction
        'If DDLConstruction.SelectedValue = 1 And DDLTop.SelectedIndex > 0 And DDLBot.SelectedIndex > 0 And ViewState("FilmTypeID") = 4 Then
        '    Call FindFilm(DDLTop.SelectedValue, DDLBot.SelectedValue)
        'End If
        'this calculates the cost of manufacturing and resets the hourlycost rate and discounteuro values in the calculation functions after the COM has been calculated
        Dim TempClothDiscount, TempHourlyRate, TempCOM As Double
        TempClothDiscount = Calculation.ClothDiscount
        TempHourlyRate = Calculation.HourlyRate
        If IsDBNull(ViewState("DiscountEuro")) Then ViewState("DiscountEuro") = 0
        Calculation.ClothDiscount = ViewState("DiscountEuro")
        Calculation.HourlyRate = ViewState("HourlyCostRate")
        Calculation.Sundries = FindSundry(Calculation.GenSailTypeID, Calculation.InputArea)
        TempCOM = Round(Calculation.FCofMFabric, 2)
        Calculation.ClothDiscount = TempClothDiscount
        Calculation.HourlyRate = TempHourlyRate
        Dim TempDept, TempLocale As Integer
        If ViewState("Accessory") = True Then
            TempDept = 5
            TempLocale = 1
        ElseIf DDLConstruction.SelectedValue = 1 Then
            TempDept = 3
            TempLocale = 5
        ElseIf Calculation.GenSailTypeID = 3 Then
            TempDept = 2
            TempLocale = 1
        Else
            TempDept = 1
            TempLocale = 1
        End If
        'Response.Write(Calculation.EMTCofM & "<br>" & Calculation.InputArea & "<br>" & Calculation.COMDPIPF & "<br>" & Calculation.YarnPriceFactor & "<br>" & Calculation.BaseAdjuster & "<br>" & Calculation.SurfaceTopPrice & "<br>" & Calculation.SurfaceBottomPrice & "<br>" & Calculation.EMTReefs & "<br>")
        'Response.Write(Calculation.EMTReefs * ((Calculation.InputArea * Calculation.COMDPIPF * Calculation.YarnPriceFactor) / 10))
        'Response.Write(" InputArea " & Calculation.InputArea & " Small Sail Adjuster " & Calculation.SmallSailAdjuster & " HoursUsedFactor " & Calculation.HoursUsedFactor & " HourlyRate " & Calculation.HourlyRate & " TierAdjuster " & Calculation.TierAdjuster & " ClothHoursFactor " & Calculation.ClothHoursFactor & "<br>")
        'Response.Write(" InputArea " & Calculation.InputArea & " Small Sail Adjuster " & Calculation.SmallSailAdjuster & " SailCostFactor " & Calculation.SailCostFactor & " ClothPricesSqm " & Calculation.ClothPriceSqm & " ClothAreaPrice " & Calculation.ClothAreaPrice & "<br>")
        'Response.Write(" BaseAdjuster " & Calculation.BaseAdjuster & " SailAdjuster " & Calculation.SailAdjuster & " UsAGEadjuster " & Calculation.UsageAdjuster & " Baseretailpricecloth " & Calculation.BaseRetailPriceCloth & "BRPad " & Calculation.BaseretailPriceAdjusted & " EMT " & Calculation.EMT & "<br>")
        If ViewState("QuoteLineItemID") > 0 Then
            MyCommand.Parameters.Clear()
            ' If ViewState("Accessory") = False Then
            MySQL = "Update QuoteLineItem_Tbl set QuoteSailTypeID=@QuoteSailTypeID, Luff=@Luff, LporFoot=@LporFoot, InputArea=@InputArea, GenericYarnID=@GenericYarnID, BoatSpeed=@BoatSpeed, AWS=@AWS, FilmTypeID=@FilmTypeID, DPIID=@DPIID, CurrencyID=@CurrencyID, Discount=@Discount, TierID=@TierID, UsageID=@UsageID,  ConstructionID=@ConstructionID, Price=@Price, SailModelCode=@SailModelCode, Cut=@Cut, Weight=@Weight, Multiple=@Multiple, TotalPrice=@TotalPrice, PreDiscountPrice=@PreDiscountPrice, BRP=@BRP, FabricID=@FabricID, NotionalArea=@NotionalArea, MarketPriceEuro=@MarketPriceEuro, MarketRetailPrice=@MarketRetailPrice, SeasonalPriceEuro=@SeasonalPriceEuro, SeasonalPriceCurr=@SeasonalPriceCurr, OptionTotal=@OptionTotal, BillingPrice=@BillingPrice, BillingDiscount=@BillingDiscount, BillingCurrency=@BillingCurrency, COM=@COM, Notes=@Notes, NotArea=@NotArea, DepartmentID=@DepartmentID, LocaleID=@LocaleID, TopSurfaceID=@TopSurfaceID, BotSurfaceID=@BotSurfaceID where QuoteLineItemID=" & ViewState("QuoteLineItemID") 'TotalOfferedPrice=@TotalOfferedPrice, 
            ' MySQLStandard = "Update OEMSailList_Tbl set QuoteSailTypeID=@QuoteSailTypeID,  [Area]=@Area, GenericYarnID=@GenericYarnID, FilmTypeID=@FilmTypeID,  CurrencyID=@CurrencyID,  TierID=@TierID, UsageID=@UsageID,  ConstructionID=@ConstructionID, MarketRetailPrice=@MarketRetailPrice,  Cut=@Cut, Weight=@Weight, FabricID=@FabricID, Notes=@Notes, SailModelCode=@SailModelCode where QuoteLineItemID=" & ViewState("QuoteLineItemID")
            MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", DDLSailType.SelectedValue)
            MyCommand.Parameters.AddWithValue("@Luff", CType(TBLuff.Text, Double))
            MyCommand.Parameters.AddWithValue("@LporFoot", CType(TBLporFoot.Text, Double))
            MyCommand.Parameters.AddWithValue("@InputArea", CType(TBInputArea.Text, Double))
            MyCommand.Parameters.AddWithValue("@GenericYarnID", DDLYarnType.SelectedValue)
            MyCommand.Parameters.AddWithValue("@BoatSpeed", CType(LblBoatSpeed.Text, Double))
            MyCommand.Parameters.AddWithValue("@AWS", DDLAWS.SelectedItem.Text)
            MyCommand.Parameters.AddWithValue("@MarketPriceEuro", Calculation.MarketRetailPriceEuro())
            MyCommand.Parameters.AddWithValue("@MarketRetailPrice", Calculation.MarketRetailPrice())
            MyCommand.Parameters.AddWithValue("@SeasonalPriceEuro", Calculation.SeasonalPrice1())
            MyCommand.Parameters.AddWithValue("@SeasonalPriceCurr", Calculation.SeasonalPrice2())
            MyCommand.Parameters.AddWithValue("@OptionTotal", Calculation.OptionTot)
            MyCommand.Parameters.AddWithValue("@FilmTypeID", ViewState("FilmTypeID"))
            If DDLConstruction.SelectedValue = 1 Then
                MyCommand.Parameters.AddWithValue("@DPIID", DDLDPI.SelectedValue)
            Else
                MyCommand.Parameters.AddWithValue("@DPIID", 0)
            End If
            MyCommand.Parameters.AddWithValue("@CurrencyID", 13)
            MyCommand.Parameters.AddWithValue("@Discount", 0) ' CType(TBDiscount.Text, Double))
            MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
            MyCommand.Parameters.AddWithValue("@UsageID", RBRaceCruise.SelectedValue)
            MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
            MyCommand.Parameters.AddWithValue("@Price", CType(LblPrice.Text, Double))
            ' MyCommand.Parameters.AddWithValue("@Price", Calculation.BaseRetailPriceCloth())
            MyCommand.Parameters.AddWithValue("@SailModelCode", Calculation.SailModelCode())
            'If ViewState("IsNylon") And DDLConstruction.SelectedValue = 5 Then
            MyCommand.Parameters.AddWithValue("@Cut", "") ' DDLCut.SelectedItem.Text)
            'Else
            ' MyCommand.Parameters.AddWithValue("@Cut", LblCut.Text)
            ' End If
            MyCommand.Parameters.AddWithValue("@Weight", ViewState("Weight"))
            MyCommand.Parameters.AddWithValue("@Multiple", 1) ' TBMultiple.Text)
            MyCommand.Parameters.AddWithValue("@TotalPrice", CType(LblPrice.Text, Double))
            ' MyCommand.Parameters.AddWithValue("@TotalOfferedPrice", TempOfferPrice * CType(TBMultiple.Text, Integer))
            MyCommand.Parameters.AddWithValue("@PreDiscountPrice", Calculation.SeasonalPrice2 * Calculation.LineItemMultiplier)
            MyCommand.Parameters.AddWithValue("@BRP", Calculation.BaseretailPriceAdjusted)
            If DDLConstruction.SelectedValue = 1 Then
                MyCommand.Parameters.AddWithValue("@FabricID", 0)
            Else
                MyCommand.Parameters.AddWithValue("@FabricID", DDLCloth.SelectedValue)
            End If
            MyCommand.Parameters.AddWithValue("@NotionalArea", 0) 'CBNotArea.Checked)
            'If CBNotArea.Checked = True Then
            '    MyCommand.Parameters.AddWithValue("@NotArea", Calculation.NotionalArea)
            'Else
            MyCommand.Parameters.AddWithValue("@NotArea", CType(0, Double))
            ' End If
            MyCommand.Parameters.AddWithValue("@BillingPrice", TempBillPrice)
            MyCommand.Parameters.AddWithValue("@BillingDiscount", TempDisc)
            MyCommand.Parameters.AddWithValue("@BillingCurrency", "GBP")
            'Try
            '    MyCommand.Parameters.AddWithValue("@COM", CType(Left(LblCOM.Text, Len(LblCOM.Text) - 2), Double))
            'Catch
            MyCommand.Parameters.AddWithValue("@COM", 0)
            'End Try
            MyCommand.Parameters.AddWithValue("@Notes", "") 'TBLINotes.Text)
            MyCommand.Parameters.AddWithValue("@DepartmentID", TempDept)
            MyCommand.Parameters.AddWithValue("@LocaleID", TempLocale)
            If DDLConstruction.SelectedValue = 1 Then
                MyCommand.Parameters.AddWithValue("@TopSurfaceID", DDLTopSurface.SelectedValue)
                MyCommand.Parameters.AddWithValue("@BotSurfaceID", DDLBotSurface.SelectedValue)
            Else
                MyCommand.Parameters.AddWithValue("@TopSurfaceID", 0)
                MyCommand.Parameters.AddWithValue("@BotSurfaceID", 0)
            End If
            'End If
            'Else ' This is the accessory
            '    MySQL = "Update QuoteLineItem_Tbl set Price=@Price, Multiple=@Multiple, TotalPrice=@TotalPrice,  MarketPriceEuro=@MarketPriceEuro, MarketRetailPrice=@MarketRetailPrice, SeasonalPriceEuro=@SeasonalPriceEuro, SeasonalPriceCurr=@SeasonalPriceCurr,   Discount=@Discount  where QuoteLineItemID=" & ViewState("QuoteLineItemID") 'TotalOfferedPrice=@TotalOfferedPrice, 
            '    MyCommand.Parameters.AddWithValue("@Price", CType(LblSellPCurrency.Text, Double)) 'TempPrice)
            '    MyCommand.Parameters.AddWithValue("@Multiple", 1) 'TBMultiple.Text)
            '    MyCommand.Parameters.AddWithValue("@TotalPrice", CType(LblTotalPRice.Text, Double))
            '    MyCommand.Parameters.AddWithValue("@MarketPriceEuro", CType(LblMRCCurrency1.Text, Double))
            '    MyCommand.Parameters.AddWithValue("@MarketRetailPrice", CType(LblMRCCurrency.Text, Double))
            '    MyCommand.Parameters.AddWithValue("@SeasonalPriceEuro", CType(LblSeason1.Text, Double))
            '    MyCommand.Parameters.AddWithValue("@SeasonalPriceCurr", CType(LblSeason2.Text, Double))
            '    MyCommand.Parameters.AddWithValue("@Discount", CType(TBDiscount.Text, Double))
            'End If '
            MyCommand.CommandText = MySQL
            MyCommand.Connection = MyConnection

            Try
                MyCommand.ExecuteNonQuery()
            Catch ex As Exception
                lblmessage.Text = lblmessage.Text & "<br>" & ex.ToString & "<br>" & MySQL
                lblmessage.Visible = True
            End Try
        End If
        Try
            If DDLConstruction.SelectedValue = 1 And DDLTopSurface.SelectedIndex > 0 And DDLBotSurface.SelectedIndex > 0 And ViewState("FilmTypeID") = 4 Then
                lblmessage.Text = "Please reselect the film surfaces" & "<br>"
                lblmessage.Visible = True
            End If
        Catch
        End Try
        'If ViewState("OEMSailListID") = 0 Then
        '    Exit Sub
        'End If
        'MyCommand.Parameters.Clear()
        'MyCommand.Parameters.AddWithValue("@QuoteSailTypeID", DDLSailType.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@Area", CType(TBInputArea.Text, Double))
        'MyCommand.Parameters.AddWithValue("@GenericYarnID", DDLYarnType.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@BoatSpeed", CType(LblBoatSpeed.Text, Double))
        'MyCommand.Parameters.AddWithValue("@FilmTypeID", ViewState("FilmTypeID"))
        'MyCommand.Parameters.AddWithValue("@DPI", DDLDPI.SelectedItem.Text)
        'MyCommand.Parameters.AddWithValue("@CurrencyID", CurrencyID)
        'MyCommand.Parameters.AddWithValue("@Discount", CType(TBDiscount.Text, Double))
        'MyCommand.Parameters.AddWithValue("@TierID", DDLTier.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@UsageID", DDLRaceCruise.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@SailModelCode", Calculation.SailModelCode)
        'MyCommand.Parameters.AddWithValue("@ConstructionID", DDLConstruction.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@Cut", LblCut.Text)
        'MyCommand.Parameters.AddWithValue("@Weight", ViewState("Weight"))
        'MyCommand.Parameters.AddWithValue("@Multiple", TBMultiple.Text)
        'MyCommand.Parameters.AddWithValue("@MarketRetailPrice", Calculation.MarketRetailPrice)
        'MyCommand.Parameters.AddWithValue("@FabricID", DDLCloth.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@TopSurfaceID", DDLTop.SelectedValue)
        'MyCommand.Parameters.AddWithValue("@BotSurfaceID", DDLBot.SelectedValue)
        ''MyCommand.Parameters.AddWithValue("@Notes", TBLINotes.Text)
        'MyCommand.Parameters.AddWithValue("@Notes", "")
        'MyCommand.CommandText = MySQLStandard
        'MyCommand.Connection = MyConnection
        'Try
        '    MyCommand.ExecuteNonQuery()
        'Catch ex As Exception
        '    LblMessage.Text = ex.ToString "
        '    lblmessage.Visible = True
        'End Try

    End Sub

    Sub CreateSummary()
        LblSumBoatType.Text = TBBoatType.Text : LblSumISP.Text = TBISP.Text : LblSumSpl.Text = TBSPL.Text
        LblSumI.Text = TBI.Text : LblSumJ.Text = TBJ.Text : LblSumP.Text = TBP.Text : LblSumE.Text = TBE.Text
        LblSumLOA.Text = TBLOA.Text
        MyCommand.Parameters.Clear()
        Try
            MyDS.Tables("LIU").Rows.Clear()
        Catch ex As Exception
        End Try
        MySQL = "SELECT QuoteLineItem_Tbl.QuoteID, QuoteLineItem_Tbl.TotalOfferedPrice, QuoteLineItem_Tbl.QuoteSailTypeID,  QuoteLineItem_Tbl.NotionalArea, (Select case when QuoteLineItem_Tbl.NotArea is null then QuoteLineItem_Tbl.InputArea else QuoteLineItem_Tbl.NotArea end) as NotArea, QuoteLineItem_Tbl.ConstructionID, QuoteLineItem_Tbl.Weight, QuoteLineItem_Tbl.QuoteLineItemID, QuoteLineItem_Tbl.Discount, QuoteLineItem_Tbl.SeasonalPriceCurr, QuoteLineItem_Tbl.SailModelCode, QuoteLineItem_Tbl.Cut, QuoteLineItem_Tbl.Multiple, (Select FilmType_Tbl.FilmType from FilmType_Tbl where QuoteLineItem_Tbl.FilmTypeID = FilmType_Tbl.FilmTypeID) as FilmType, (Select Tier_Tbl.Tier from Tier_Tbl where QuoteLineItem_Tbl.TierID = Tier_Tbl.TierID) as Tier, (Select ConstructionAndrew_Tbl.Construction from ConstructionAndrew_Tbl where QuoteLineItem_Tbl.ConstructionID = ConstructionAndrew_Tbl.ConstructionID) as Construction, (Select ConstructionAndrew_Tbl.ConstructionCode from ConstructionAndrew_Tbl where QuoteLineItem_Tbl.ConstructionID = ConstructionAndrew_Tbl.ConstructionID) as ConstructionCode, (Select GenericYarn_Tbl.YarnType FROM GenericYarn_Tbl where QuoteLineItem_Tbl.GenericYarnID = GenericYarn_Tbl.GenericYarnID) as YarnType, (select QuoteSailType_Tbl.SailType from QuoteSailType_Tbl where QuoteLineItem_Tbl.QuoteSailtypeID = QuoteSailType_Tbl.QuoteSailTypeID) as Sailtype, (select QuoteSailType_Tbl.Furling from QuoteSailType_Tbl where QuoteLineItem_Tbl.QuoteSailtypeID = QuoteSailType_Tbl.QuoteSailTypeID) as Furling, (select TargetDPI_Tbl.TargetDPI from TargetDPI_Tbl where QuoteLineItem_Tbl.DPIID = TargetDPI_Tbl.TargetDPIID) as DPI,  (Select Fabric_Tbl.PartCode from Fabric_Tbl where QuoteLineItem_Tbl.FabricID = Fabric_Tbl.FabricID) as PartCode, QuoteLineItem_Tbl.InputArea, QuoteLineItem_Tbl.AccessoryID, QuoteLineItem_Tbl.Price  from QuoteLineItem_Tbl  WHERE QuoteLineItem_Tbl.QuoteID = @QuoteID order by QuoteLineItem_Tbl.Lineitem"
        MyCommand.Parameters.AddWithValue("@QuoteID", ViewState("QuoteID"))
        MyCommand.Parameters.AddWithValue("@Weekno", DatePart(DateInterval.WeekOfYear, DelDate, , FirstWeekOfYear.FirstFourDays))
        MyCommand.Connection = MyConnection
        MyCommand.CommandText = MySQL
        MyDA.SelectCommand = MyCommand
        ' Try
        MyDA.Fill(MyDS, "LIU")
        lblmessage.Text = lblmessage.Text & " " & MyDS.tables("LIU").rows.count
        For i = 0 To MyDS.tables("LIU").rows.count - 1
            TblRow = New TableRow
            TblCell = New TableCell
            MyLbl = New Label
            MyLbl.CssClass = "fieldtext"
            MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("SailType")
            TblCell.Controls.Add(MyLbl)
            TblRow.Controls.Add(TblCell)
            TblCell = New TableCell
            MyLbl = New Label
            MyLbl.CssClass = "fieldtext"
            MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("InputArea")
            TblCell.Controls.Add(MyLbl)
            TblRow.Controls.Add(TblCell)
            TblCell = New TableCell
            MyLbl = New Label
            MyLbl.CssClass = "fieldtext"
            MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("Construction")
            TblCell.Controls.Add(MyLbl)
            TblRow.Controls.Add(TblCell)
            TblCell = New TableCell
            MyLbl = New Label
            MyLbl.CssClass = "fieldtext"
            '  If MyDS.Tables("LIU").Rows(i).Item("ConstructionID") = 1 Then
            MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("YarnType")
            '  Else
            '  MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("Fabric")
            '  End If
            TblCell.Controls.Add(MyLbl)
            TblRow.Controls.Add(TblCell)
            TblCell = New TableCell
            MyLbl = New Label
            MyLbl.CssClass = "fieldtext"
            If MyDS.Tables("LIU").Rows(i).Item("ConstructionID") = 1 Then
                MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("DPI")
            Else
                MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("Weight") & "g"
            End If
            TblCell.Controls.Add(MyLbl)
            TblRow.Controls.Add(TblCell)
            TblCell = New TableCell
            MyLbl = New Label
            MyLbl.CssClass = "fieldtextbold"
            MyLbl.Text = MyDS.Tables("LIU").Rows(i).Item("SeasonalPriceCurr")
            TblCell.Controls.Add(MyLbl)
            TblRow.Controls.Add(TblCell)
            TblLineItem.Rows.Add(TblRow)
        Next
    End Sub

End Class